Skip to content

AlphaEvolve Runtime Harness (evolve)

evolve

Opt-In AlphaEvolve & Vertex AI Gemini Evolutionary Harness (scale_forecasting.evolve).

Provides opt-in runtime evolutionary code synthesis built directly on top of :meth:~scale_forecasting.sdk.Forecaster.auto (auto.py / auto_policy.py) and governed by a 3-Gate Anti-Overfitting Ratchet:

  • Dual-Backend Evolution Transport (:mod:~scale_forecasting.evolve.client):
  • backend="alphaevolve" (Default): Managed Gemini Enterprise Discovery Engine AlphaEvolve REST API (discoveryengine.googleapis.com/v1alpha), guarded by a fast pre-flight access probe (:func:probe_alphaevolve_access) before any backtests run.
  • backend="vertex_gemini" (Backup Non-Default): Standard Vertex AI Gemini (aiplatform.googleapis.com, default "gemini-3.8-flash" or any user-specified model_name) with an in-memory multi-island MAP-Elites population buffer (:class:IslandPopulationBuffer) for projects without Gemini Enterprise licensing.
  • backend="mock" (Offline Test Backend): Deterministic zero-network candidate replay.
  • Five # EVOLVE-BLOCK Targets (:mod:~scale_forecasting.evolve.targets): "features" (:func:synthesize_evolved_features), "ensemble" (:func:compute_evolved_weights), "model" (:class:EvolvedForecaster), "policy" (:func:evolve_policy_weights), and "similarity_kernel" (:func:compute_evolved_similarity_kernel).
  • AST Security & Temporal Causality Sandbox (:mod:~scale_forecasting.evolve.sandbox): Static AST whitelist (:func:validate_candidate_ast) plus the $+10^6$ future-target perturbation test (:func:verify_no_future_leakage).
  • 3-Gate Anti-Overfitting Ratchet (:mod:~scale_forecasting.evolve.evaluator & :mod:~scale_forecasting.evolve.runner): Gate 1 (Inner Walk-Forward CV Lift), Gate 2 (Diebold–Mariano significance & worst-decile FVA guard), and Gate 3 (Held-Out Lockdown Fold never seen by the evolution loop).

AlphaEvolveClient

AlphaEvolveClient(
    project_id=None,
    location="global",
    *,
    model_name=DEFAULT_GEMINI_MODEL,
    timeout=30.0,
    http_request=None,
)

Managed Discovery Engine AlphaEvolve REST transport (backend='alphaevolve').

Source code in src/scale_forecasting/evolve/client.py
def __init__(
    self,
    project_id: str | None = None,
    location: str = "global",
    *,
    model_name: str = DEFAULT_GEMINI_MODEL,
    timeout: float = 30.0,
    http_request: Callable[..., dict[str, Any]] | None = None,
) -> None:
    self.project_id = _resolve_project_id(project_id)
    self.location = location
    self.model_name = model_name
    self.timeout = timeout
    self._http_request = http_request
    self._experiment_name: str | None = None

base_url property

base_url

Return the regional/global alphaEvolveExperiments collection URL.

acquire_programs

acquire_programs(experiment_name=None, count=1)

Acquire mutated candidate programs via :acquirePrograms.

Source code in src/scale_forecasting/evolve/client.py
def acquire_programs(
    self,
    experiment_name: str | None = None,
    count: int = 1,
) -> list[dict[str, Any]]:
    """Acquire mutated candidate programs via ``:acquirePrograms``."""
    exp = experiment_name or self._experiment_name
    if not exp:
        raise ConfigurationError(
            "create_experiment() must be called before acquire_programs()."
        )
    if exp.startswith(("http://", "https://")):
        url = f"{exp}:acquirePrograms"
    else:
        url = (
            f"https://discoveryengine.googleapis.com/v1alpha/{exp.lstrip('/')}:acquirePrograms"
        )
    resp = self._post_json(url, {"programCount": max(1, int(count))})
    programs = resp.get("programs", [])
    if isinstance(programs, list) and programs:
        return [dict(p) for p in programs if isinstance(p, Mapping)]
    return []

create_experiment

create_experiment(
    target, seed_code, system_instruction="", config=None
)

Create a managed alphaEvolveExperiments resource in Discovery Engine.

Source code in src/scale_forecasting/evolve/client.py
def create_experiment(
    self,
    target: str,
    seed_code: str,
    system_instruction: str = "",
    config: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
    """Create a managed ``alphaEvolveExperiments`` resource in Discovery Engine."""
    payload: dict[str, Any] = {
        "displayName": f"scale-forecasting-evolve-{target}",
        "target": target,
        "modelName": self.model_name,
        "seedProgram": {"code": seed_code},
        "systemInstruction": system_instruction,
    }
    if config:
        payload["experimentConfig"] = dict(config)
    resp = self._post_json(self.base_url, payload)
    exp_name = str(
        resp.get(
            "name",
            f"projects/{self.project_id}/locations/{self.location}/"
            f"alphaEvolveExperiments/exp-{target}",
        )
    )
    self._experiment_name = exp_name
    return {"name": exp_name, **resp}

probe_access

probe_access()

Run the pre-flight access probe against discoveryengine.googleapis.com.

Source code in src/scale_forecasting/evolve/client.py
def probe_access(self) -> dict[str, Any]:
    """Run the pre-flight access probe against ``discoveryengine.googleapis.com``."""
    return probe_alphaevolve_access(
        self.project_id,
        self.location,
        timeout=min(self.timeout, 10.0),
    )

propose_candidate

propose_candidate(
    target, parent_code, diagnostics=None, generation=1
)

Acquire the next candidate program from the managed AlphaEvolve experiment.

Source code in src/scale_forecasting/evolve/client.py
def propose_candidate(
    self,
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Acquire the next candidate program from the managed AlphaEvolve experiment."""
    spec = get_target_seed(target)
    if self._experiment_name is None:
        self.create_experiment(
            target=spec.target,
            seed_code=parent_code,
            system_instruction=spec.system_instruction,
        )
    programs = self.acquire_programs(self._experiment_name, count=1)
    if programs and "code" in programs[0]:
        raw_code = str(programs[0]["code"])
        try:
            injected = inject_evolve_block(spec.seed_code, raw_code)
            if validate_candidate_ast(injected).valid:
                return injected
        except Exception as exc:  # noqa: BLE001 - fallback when raw program is malformed
            _log.debug("Acquired AlphaEvolve program failed AST validation: %s", exc)
        cands = deterministic_mock_candidates(spec.target, count=max(1, generation))
        return cands[(generation - 1) % len(cands)]
    _ = (diagnostics, generation)
    return parent_code

record_evaluation

record_evaluation(
    program_id, code, score, diagnostics=None
)

Report candidate evaluation fitness back to Discovery Engine AlphaEvolve.

Source code in src/scale_forecasting/evolve/client.py
def record_evaluation(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
) -> None:
    """Report candidate evaluation fitness back to Discovery Engine AlphaEvolve."""
    if self._experiment_name is None:
        return
    self.submit_evaluations(
        self._experiment_name,
        [
            {
                "programId": program_id,
                "code": code,
                "fitnessScore": float(-score if math.isfinite(score) else -1e6),
                "metrics": dict(diagnostics or {}),
            }
        ],
    )

submit_evaluations

submit_evaluations(experiment_name=None, evaluations=())

Submit walk-forward evaluation scores via :submitProgramsEvaluations.

Source code in src/scale_forecasting/evolve/client.py
def submit_evaluations(
    self,
    experiment_name: str | None = None,
    evaluations: Sequence[Mapping[str, Any]] = (),
) -> dict[str, Any]:
    """Submit walk-forward evaluation scores via ``:submitProgramsEvaluations``."""
    exp = experiment_name or self._experiment_name
    if not exp:
        raise ConfigurationError(
            "create_experiment() must be called before submit_evaluations()."
        )
    if exp.startswith(("http://", "https://")):
        url = f"{exp}:submitProgramsEvaluations"
    else:
        url = (
            "https://discoveryengine.googleapis.com/v1alpha/"
            f"{exp.lstrip('/')}:submitProgramsEvaluations"
        )
    return self._post_json(
        url,
        {"programEvaluations": [dict(e) for e in evaluations]},
    )

AutoPolicyWeights dataclass

AutoPolicyWeights(
    intermittent_share_min=0.165,
    log1p_level_vol_corr_min=0.635,
    log1p_growth_ratio_min=1.336,
    resid_hetero_min=0.3,
    structural_break_share_min=0.251,
    outlier_spike_share_min=0.195,
    direct_horizon_decay_ratio_min=1.323,
    resid_acf1_escalate_min=0.309,
    fva_escalate_min_pct=3.077,
    white_noise_growth_tol=0.179,
    white_noise_acf_season_max=0.17,
    require_white_noise_stop=True,
    pass_decay_factor=0.7,
    first_light_include_regression_lags=True,
    first_light_selection_rule="best_single",
    tree_n_estimators_fast=60,
    enable_similarity_global=True,
    similarity_silhouette_threshold=0.3,
    action_weights=_default_action_weights(),
)

Typed container of evolutionary thresholds for :mod:scale_forecasting.auto_policy.

from_defaults classmethod

from_defaults()

Construct :class:AutoPolicyWeights from auto_policy.evolved_policy_thresholds().

Source code in src/scale_forecasting/evolve/targets.py
@classmethod
def from_defaults(cls) -> AutoPolicyWeights:
    """Construct :class:`AutoPolicyWeights` from ``auto_policy.evolved_policy_thresholds()``."""
    return cls.from_dict(evolved_policy_thresholds())

from_dict classmethod

from_dict(data)

Construct :class:AutoPolicyWeights from a plain threshold dictionary.

Source code in src/scale_forecasting/evolve/targets.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> AutoPolicyWeights:
    """Construct :class:`AutoPolicyWeights` from a plain threshold dictionary."""
    valid_fields = set(cls.__dataclass_fields__)
    filtered: dict[str, Any] = {}
    for k, v in data.items():
        if k not in valid_fields:
            continue
        if k == "action_weights" and isinstance(v, Mapping):
            filtered[k] = {
                str(ak): (float(av[0]), float(av[1]))
                for ak, av in v.items()
                if isinstance(av, (tuple, list)) and len(av) == 2
            }
        else:
            filtered[k] = v
    return cls(**filtered)

to_dict

to_dict()

Serialize policy weights to a dictionary compatible with auto_policy.

Source code in src/scale_forecasting/evolve/targets.py
def to_dict(self) -> dict[str, Any]:
    """Serialize policy weights to a dictionary compatible with ``auto_policy``."""
    out = asdict(self)
    out["first_light_ensemble_strategies"] = ["inverse_error", "mean"]
    return out

with_updates

with_updates(**kwargs)

Return a copy of self with updated field values.

Source code in src/scale_forecasting/evolve/targets.py
def with_updates(self, **kwargs: Any) -> AutoPolicyWeights:
    """Return a copy of ``self`` with updated field values."""
    return replace(self, **kwargs)

CandidateEvaluation dataclass

CandidateEvaluation(
    candidate_id,
    generation,
    target,
    backend,
    code,
    ast_valid,
    causal_valid,
    inner_cv_score,
    baseline_score,
    inner_fva_pct,
    dm_stat,
    dm_pvalue,
    worst_decile_fva_pct,
    gate1_passed,
    gate2_passed,
    lockdown_baseline_score,
    lockdown_candidate_score,
    gate3_passed,
    promoted,
    status,
    rejection_reason,
    wall_seconds,
    series_losses_candidate=(),
    series_losses_baseline=(),
    point_losses_candidate=(),
    point_losses_baseline=(),
)

Complete evaluation telemetry for one candidate program across all 3 ratchet gates.

to_row

to_row()

Convert candidate evaluation to a flat leaderboard row dictionary.

Source code in src/scale_forecasting/evolve/evaluator.py
def to_row(self) -> dict[str, Any]:
    """Convert candidate evaluation to a flat leaderboard row dictionary."""
    return {
        "candidate_id": self.candidate_id,
        "generation": self.generation,
        "target": self.target,
        "backend": self.backend,
        "ast_valid": self.ast_valid,
        "causal_valid": self.causal_valid,
        "inner_cv_score": (
            round(self.inner_cv_score, 6) if math.isfinite(self.inner_cv_score) else None
        ),
        "baseline_score": (
            round(self.baseline_score, 6) if math.isfinite(self.baseline_score) else None
        ),
        "inner_fva_pct": (
            round(self.inner_fva_pct, 4) if math.isfinite(self.inner_fva_pct) else 0.0
        ),
        "dm_pvalue": round(self.dm_pvalue, 6) if math.isfinite(self.dm_pvalue) else None,
        "worst_decile_fva_pct": (
            round(self.worst_decile_fva_pct, 4)
            if math.isfinite(self.worst_decile_fva_pct)
            else None
        ),
        "gate1_passed": self.gate1_passed,
        "gate2_passed": self.gate2_passed,
        "lockdown_baseline_score": (
            round(self.lockdown_baseline_score, 6)
            if math.isfinite(self.lockdown_baseline_score)
            else None
        ),
        "lockdown_candidate_score": (
            round(self.lockdown_candidate_score, 6)
            if math.isfinite(self.lockdown_candidate_score)
            else None
        ),
        "gate3_passed": self.gate3_passed,
        "promoted": self.promoted,
        "status": self.status,
        "rejection_reason": self.rejection_reason,
        "wall_seconds": round(self.wall_seconds, 4),
    }

EvolutionEvaluator

EvolutionEvaluator(
    data_df=None,
    *,
    from_runs=None,
    from_run_ids=None,
    dataset_id="scale_forecasting",
    project_id=None,
    region="us-central1",
    target="features",
    backend="alphaevolve",
    tier="first_light",
    where="local",
    horizon=None,
    significance_alpha=0.1,
    worst_decile_floor=-0.02,
    timeout_seconds=20.0,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    freq=None,
)

Evaluates candidate # EVOLVE-BLOCK programs on top of Forecaster.auto() or prior runs.

Source code in src/scale_forecasting/evolve/evaluator.py
def __init__(
    self,
    data_df: pd.DataFrame | Any = None,
    *,
    from_runs: Sequence[Any] | None = None,
    from_run_ids: Sequence[str] | None = None,
    dataset_id: str = "scale_forecasting",
    project_id: str | None = None,
    region: str = "us-central1",
    target: str = "features",
    backend: str = "alphaevolve",
    tier: str = "first_light",
    where: str = "local",
    horizon: int | None = None,
    significance_alpha: float = 0.10,
    worst_decile_floor: float = -0.02,
    timeout_seconds: float = 20.0,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    freq: str | None = None,
) -> None:
    self.target = get_target_seed(target).target
    self.backend = backend
    self.tier = tier
    self.where = where
    self.significance_alpha = significance_alpha
    self.worst_decile_floor = worst_decile_floor
    self.timeout_seconds = timeout_seconds
    self.lockdown_oof_df: pd.DataFrame = pd.DataFrame()
    self.pool_diagnostics: dict[str, Any] = {}
    self.reigning_champion_model: str = ""

    # Detect whether we are running in post-run pool mode (zero base-model refitting)
    runs_list: list[Any] = []
    if from_runs is not None:
        runs_list.extend(from_runs)
    if from_run_ids is not None:
        runs_list.extend(from_run_ids)
    if data_df is not None and not isinstance(data_df, pd.DataFrame):
        runs_list.insert(0, data_df)

    if runs_list:
        self.mode = "post_run_pool"
        self.ts_id_col = "ts_id"
        self.date_col = "ds"
        self.target_col = "y"
        pool_bundle = verify_oof_pool_compatibility(
            runs_list,
            project_id=project_id,
            dataset_id=dataset_id,
            region=region,
            horizon=horizon,
        )
        self.oof_df = pool_bundle["inner_oof_df"].copy()
        self.lockdown_oof_df = pool_bundle["lockdown_oof_df"].copy()
        self.raw_predictions_df = pool_bundle["pooled_predictions_df"].copy()
        self.reigning_champion_model = str(pool_bundle["reigning_champion_model"])
        self.pool_diagnostics = dict(pool_bundle["pool_diagnostics"])
        self.forecaster = pool_bundle.get("primary_forecaster")
        self.session = getattr(self.forecaster, "auto_session", None)
        self.profile = getattr(self.session, "profile", None)
        self.profile_dict: dict[str, Any] = (
            self.profile.to_dict()
            if self.profile is not None and hasattr(self.profile, "to_dict")
            else {
                "n_series": int(self.oof_df["ts_id"].nunique()),
                "models_pooled": self.pool_diagnostics.get("models_pooled", []),
                "reigning_champion_model": self.reigning_champion_model,
            }
        )
        self.horizon = int(
            horizon
            if horizon is not None
            else max(1, int(self.pool_diagnostics.get("lockdown_oof_timestamps", 7)))
        )
        # Reconstruct a lightweight inner_df from inner_oof_df for feature/model fallback
        self.inner_df = (
            self.oof_df.groupby(["ts_id", "ds"], as_index=False)
            .agg({"y_true": "first"})
            .rename(columns={"y_true": "y"})
        )
        self.lockdown_truth_df = (
            self.lockdown_oof_df.groupby(["ts_id", "ds"], as_index=False)
            .agg({"y_true": "first"})
            .rename(columns={"y_true": "y"})
        )
        self.lockdown_future_exog_df = self.lockdown_truth_df[["ts_id", "ds"]].copy()
    else:
        self.mode = "raw_panel"
        if not isinstance(data_df, pd.DataFrame):
            raise ConfigError(
                "EvolutionEvaluator requires a pandas DataFrame or from_runs/from_run_ids."
            )
        self.ts_id_col = ts_id_col if ts_id_col in data_df.columns else "ts_id"
        self.date_col = date_col if date_col in data_df.columns else "ds"
        self.target_col = target_col if target_col in data_df.columns else "y"

        work = data_df.copy()
        if self.ts_id_col not in work.columns:
            work[self.ts_id_col] = "series_0"
        counts = work.groupby(self.ts_id_col)[self.target_col].count()
        min_obs = int(counts.min()) if not counts.empty else 28
        self.horizon = int(horizon) if horizon is not None else max(3, min(7, min_obs // 5))

        (
            self.inner_df,
            self.lockdown_truth_df,
            self.lockdown_future_exog_df,
        ) = split_inner_and_lockdown_panel(
            work,
            self.horizon,
            ts_id_col=self.ts_id_col,
            date_col=self.date_col,
            target_col=self.target_col,
        )

        # Run Forecaster.auto() on the Inner Evolution Panel to establish cached OOF bank
        y_vals_fp = pd.to_numeric(self.inner_df[self.target_col], errors="coerce").fillna(0.0)
        cache_key = (
            len(self.inner_df),
            tuple(self.inner_df.columns),
            round(float(y_vals_fp.sum()), 6),
            round(float(y_vals_fp.iloc[0]) if len(y_vals_fp) else 0.0, 6),
            round(float(y_vals_fp.iloc[-1]) if len(y_vals_fp) else 0.0, 6),
            self.horizon,
            freq,
        )
        cached_forecaster = _BASELINE_SESSION_CACHE.get(cache_key)
        if cached_forecaster is None:
            fast_models = ["naive_seasonal", "naive_drift", "holtwinters"]
            exog_only_cols = [
                c
                for c in self.lockdown_future_exog_df.columns
                if c not in (self.ts_id_col, self.date_col, self.target_col)
                and pd.api.types.is_numeric_dtype(self.lockdown_future_exog_df[c])
            ]
            fut_exog_arg = (
                self.lockdown_future_exog_df[[self.ts_id_col, self.date_col, *exog_only_cols]]
                if exog_only_cols
                else None
            )
            cached_forecaster = auto_forecast(
                self.inner_df,
                future_df=fut_exog_arg,
                tier="wide_field",
                where="local",
                models=fast_models,
                baselines=["naive_seasonal"],
                hpo=False,
                calibration=False,
                explainability=False,
                n_folds=1,
                autofocus=False,
                horizon=self.horizon,
                ts_id_col=self.ts_id_col,
                date_col=self.date_col,
                target_col=self.target_col,
                freq=freq,
            )
            if len(_BASELINE_SESSION_CACHE) < 16:
                _BASELINE_SESSION_CACHE[cache_key] = cached_forecaster
        self.forecaster = cached_forecaster
        self.session = self.forecaster.auto_session
        self.profile = self.session.profile
        self.profile_dict = self.profile.to_dict()
        self.oof_df = self.session.oof_df.copy()
        self.raw_predictions_df = self.session.raw_predictions_df.copy()

    self.simplex_sum: float | None = self._resolve_evaluator_simplex_sum()
    self.hierarchy_spec: HierarchySpec | None = self._resolve_evaluator_hierarchy_spec()
    if (
        self.mode == "raw_panel"
        and self.hierarchy_spec is not None
        and not self.lockdown_truth_df.empty
        and "__total__" not in set(self.lockdown_truth_df[self.ts_id_col].astype(str))
    ):
        f_cfg = getattr(self.forecaster, "config", None) or getattr(
            self.forecaster, "_config", None
        )
        if (
            f_cfg is not None
            and getattr(f_cfg, "hierarchy", None) is not None
            and f_cfg.hierarchy.enabled
            and f_cfg.hierarchy.levels
            and all(
                c in self.lockdown_truth_df.columns
                for lvl in f_cfg.hierarchy.levels
                for c in (lvl if isinstance(lvl, (list, tuple)) else [lvl])
            )
        ):
            with contextlib.suppress(Exception):
                self.lockdown_truth_df, _ = build_hierarchy(self.lockdown_truth_df, f_cfg)

    # Precompute baseline inner CV losses and held-out lockdown fold losses for the target
    (
        self.baseline_score,
        self.series_losses_base,
        self.point_losses_base,
        self.lockdown_baseline_score,
    ) = self._compute_target_baselines()

evaluate_candidate_inner

evaluate_candidate_inner(code, *, generation=1)

Evaluate code through Pre-Gate (AST + Causality), Gate 1, and Gate 2.

Source code in src/scale_forecasting/evolve/evaluator.py
def evaluate_candidate_inner(
    self,
    code: str,
    *,
    generation: int = 1,
) -> CandidateEvaluation:
    """Evaluate ``code`` through Pre-Gate (AST + Causality), Gate 1, and Gate 2."""
    t0 = time.monotonic()
    cand_id = f"cand_{self.target}_g{generation:02d}"
    spec = get_target_seed(self.target)

    # Pre-Gate 1: AST Security Sandbox
    ast_res = validate_candidate_ast(code)
    if not ast_res.valid:
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=False,
            causal_valid=False,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_ast",
            rejection_reason=f"Pre-Gate AST Sandbox Violation: {ast_res.reason}",
            wall_seconds=time.monotonic() - t0,
        )

    try:
        symbol = compile_candidate_symbol(code, spec.entrypoint)
    except Exception as exc:  # noqa: BLE001 - compilation failure rejected cleanly
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=False,
            causal_valid=False,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_compile",
            rejection_reason=f"Candidate compilation error: {exc}",
            wall_seconds=time.monotonic() - t0,
        )

    # Pre-Gate 2: Temporal Causality / Future-Leakage Detector
    causal_ok = True
    if self.target in ("features", "model"):
        causal_ok = verify_no_future_leakage(
            symbol,
            self.inner_df,
            target_col=self.target_col,
            time_col=self.date_col,
            id_col=self.ts_id_col,
            horizon=self.horizon,
        )
    if not causal_ok:
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=True,
            causal_valid=False,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_leakage",
            rejection_reason=(
                "Pre-Gate Temporal Causality Violation: candidate failed "
                "verify_no_future_leakage() (perturbing y[T-H:] += 1e6 "
                "altered earlier timestamps)."
            ),
            wall_seconds=time.monotonic() - t0,
        )

    # Inner Walk-Forward CV Evaluation
    try:
        if self.target == "features":
            s_cand, p_cand = self._eval_features_ridge(
                self.inner_df, feature_fn=symbol, is_lockdown=False
            )
        elif self.target == "ensemble":
            w_cand = execute_in_sandbox(
                code,
                spec.entrypoint,
                self.oof_df.copy(),
                self.profile_dict,
                timeout_seconds=self.timeout_seconds,
            )
            if (
                not isinstance(w_cand, (Mapping, pd.DataFrame))
                or (isinstance(w_cand, Mapping) and not w_cand)
                or (isinstance(w_cand, pd.DataFrame) and w_cand.empty)
            ):
                raise ValueError(
                    "compute_evolved_weights returned empty or unsupported weights."
                )
            s_cand, p_cand = self._score_ensemble_weights_inner(w_cand)
        elif self.target == "model":
            s_cand, p_cand = self._eval_model_class(symbol, is_lockdown=False)
        elif self.target == "similarity_kernel":
            s_cand, p_cand = self._eval_similarity_kernel(
                self.inner_df, kernel_fn=symbol, is_lockdown=False
            )
        else:
            # target == "policy"
            base_w = AutoPolicyWeights.from_defaults()
            evolved_w = execute_in_sandbox(
                code,
                spec.entrypoint,
                base_w,
                timeout_seconds=self.timeout_seconds,
            )
            if isinstance(evolved_w, Mapping):
                evolved_w = AutoPolicyWeights.from_dict(evolved_w)
            if not isinstance(evolved_w, AutoPolicyWeights):
                raise ValueError("evolve_policy_weights must return AutoPolicyWeights.")
            # Weight the best models in oof_df using the evolved policy's decay/confidence
            decay = max(0.1, min(0.99, float(evolved_w.pass_decay_factor)))
            w_pol: dict[str, float] = {}
            for m_name, grp_m in self.oof_df.groupby("model_type", sort=False):
                if str(m_name).startswith("ensemble_"):
                    continue
                yt = pd.to_numeric(grp_m["y_true"], errors="coerce").to_numpy(dtype=float)
                yh = pd.to_numeric(grp_m["yhat"], errors="coerce").to_numpy(dtype=float)
                loss_m = max(1e-6, _series_wape(yt, yh))
                w_pol[str(m_name)] = 1.0 / (loss_m ** (2.0 / decay))
            tot_w = sum(w_pol.values()) or 1.0
            w_pol = {k: v / tot_w for k, v in w_pol.items()}
            s_cand, p_cand = self._score_ensemble_weights_inner(w_pol)
    except Exception as exc:  # noqa: BLE001 - runtime exception inside candidate
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=True,
            causal_valid=True,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_runtime",
            rejection_reason=f"Candidate execution failed on Inner CV: {exc}",
            wall_seconds=time.monotonic() - t0,
        )

    stats = _compute_ratchet_stats(
        s_cand,
        self.series_losses_base,
        p_cand,
        self.point_losses_base,
        significance_alpha=self.significance_alpha,
        worst_decile_floor=self.worst_decile_floor,
    )
    status = (
        "passed_inner_gates"
        if (stats["gate1_passed"] and stats["gate2_passed"])
        else ("rejected_gate1" if not stats["gate1_passed"] else "rejected_gate2")
    )
    return CandidateEvaluation(
        candidate_id=cand_id,
        generation=generation,
        target=self.target,
        backend=self.backend,
        code=code,
        ast_valid=True,
        causal_valid=True,
        inner_cv_score=float(stats["inner_cv_score"]),
        baseline_score=self.baseline_score,
        inner_fva_pct=float(stats["inner_fva_pct"]),
        dm_stat=float(stats["dm_stat"]),
        dm_pvalue=float(stats["dm_pvalue"]),
        worst_decile_fva_pct=float(stats["worst_decile_fva_pct"]),
        gate1_passed=bool(stats["gate1_passed"]),
        gate2_passed=bool(stats["gate2_passed"]),
        lockdown_baseline_score=self.lockdown_baseline_score,
        lockdown_candidate_score=float("nan"),
        gate3_passed=False,
        promoted=False,
        status=status,
        rejection_reason=stats["rejection_reason"],
        wall_seconds=time.monotonic() - t0,
        series_losses_candidate=tuple(s_cand),
        series_losses_baseline=tuple(self.series_losses_base),
        point_losses_candidate=tuple(p_cand),
        point_losses_baseline=tuple(self.point_losses_base),
    )

evaluate_lockdown_gate3

evaluate_lockdown_gate3(cand_eval)

Evaluate the winning inner-CV candidate once on the Held-Out Lockdown Fold.

Source code in src/scale_forecasting/evolve/evaluator.py
def evaluate_lockdown_gate3(
    self,
    cand_eval: CandidateEvaluation,
) -> CandidateEvaluation:
    """Evaluate the winning inner-CV candidate **once** on the Held-Out Lockdown Fold."""
    t0 = time.monotonic()
    spec = get_target_seed(self.target)
    try:
        symbol = compile_candidate_symbol(cand_eval.code, spec.entrypoint)
        if self.target == "features":
            s_lock, _ = self._eval_features_ridge(
                self.inner_df,
                feature_fn=symbol,
                is_lockdown=True,
                lockdown_truth_df=self.lockdown_truth_df,
            )
            lock_cand_score = float(np.mean(s_lock)) if s_lock else float("inf")
        elif self.target == "ensemble":
            w_cand = symbol(self.oof_df.copy(), self.profile_dict)
            lock_cand_score = self._score_ensemble_weights_lockdown(w_cand)
        elif self.target == "model":
            s_lock, _ = self._eval_model_class(symbol, is_lockdown=True)
            lock_cand_score = float(np.mean(s_lock)) if s_lock else float("inf")
        elif self.target == "similarity_kernel":
            s_lock, _ = self._eval_similarity_kernel(
                self.inner_df,
                kernel_fn=symbol,
                is_lockdown=True,
                lockdown_truth_df=self.lockdown_truth_df,
            )
            lock_cand_score = float(np.mean(s_lock)) if s_lock else float("inf")
        else:
            base_w = AutoPolicyWeights.from_defaults()
            evolved_w = symbol(base_w)
            if isinstance(evolved_w, Mapping):
                evolved_w = AutoPolicyWeights.from_dict(evolved_w)
            decay = max(0.1, min(0.99, float(evolved_w.pass_decay_factor)))
            w_pol: dict[str, float] = {}
            for m_name, grp_m in self.oof_df.groupby("model_type", sort=False):
                if str(m_name).startswith("ensemble_"):
                    continue
                yt = pd.to_numeric(grp_m["y_true"], errors="coerce").to_numpy(dtype=float)
                yh = pd.to_numeric(grp_m["yhat"], errors="coerce").to_numpy(dtype=float)
                loss_m = max(1e-6, _series_wape(yt, yh))
                w_pol[str(m_name)] = 1.0 / (loss_m ** (2.0 / decay))
            tot_w = sum(w_pol.values()) or 1.0
            w_pol = {k: v / tot_w for k, v in w_pol.items()}
            lock_cand_score = self._score_ensemble_weights_lockdown(w_pol)
    except Exception as exc:  # noqa: BLE001 - lockdown runtime failure rejects at Gate 3
        return CandidateEvaluation(
            **{
                **cand_eval.__dict__,
                "lockdown_candidate_score": float("inf"),
                "gate3_passed": False,
                "promoted": False,
                "status": "rejected_gate3",
                "rejection_reason": (
                    "Gate 3 (Held-Out Lockdown Fold): "
                    f"execution failed on lockdown fold ({exc})."
                ),
                "wall_seconds": cand_eval.wall_seconds + (time.monotonic() - t0),
            }
        )

    gate3_passed = bool(
        math.isfinite(lock_cand_score) and lock_cand_score < self.lockdown_baseline_score - 1e-9
    )
    promoted = bool(cand_eval.gate1_passed and cand_eval.gate2_passed and gate3_passed)
    if promoted:
        status = "promoted_champion"
        rejection_reason = None
    elif not cand_eval.gate1_passed or not cand_eval.gate2_passed:
        status = cand_eval.status
        rejection_reason = cand_eval.rejection_reason
    else:
        status = "rejected_gate3"
        rejection_reason = (
            f"Gate 3 (Held-Out Lockdown Fold): candidate improved inner CV "
            f"({cand_eval.inner_cv_score:.4f} < {cand_eval.baseline_score:.4f}) "
            f"but degraded or failed to beat baseline on the unseen lockdown fold "
            f"({lock_cand_score:.4f} >= {self.lockdown_baseline_score:.4f}). "
            f"Ratcheted back to Forecaster.auto() baseline."
        )

    return CandidateEvaluation(
        **{
            **cand_eval.__dict__,
            "lockdown_candidate_score": lock_cand_score,
            "gate3_passed": gate3_passed,
            "promoted": promoted,
            "status": status,
            "rejection_reason": rejection_reason,
            "wall_seconds": cand_eval.wall_seconds + (time.monotonic() - t0),
        }
    )

materialize_ensemble_predictions

materialize_ensemble_predictions(
    weights, *, model_label="ensemble_evolved"
)

Materialize blended forward forecasts with empirical conformal 80% intervals.

Source code in src/scale_forecasting/evolve/evaluator.py
def materialize_ensemble_predictions(
    self,
    weights: Any,
    *,
    model_label: str = "ensemble_evolved",
) -> pd.DataFrame:
    """Materialize blended forward forecasts with empirical conformal 80% intervals."""
    source_preds = self.raw_predictions_df.copy()
    date_col = "forecast_date"
    if source_preds.empty and not self.lockdown_oof_df.empty:
        source_preds = self.lockdown_oof_df.copy()
        if "forecast_date" not in source_preds.columns and "ds" in source_preds.columns:
            source_preds["forecast_date"] = source_preds["ds"]
    if source_preds.empty:
        return pd.DataFrame(
            columns=["ts_id", "forecast_date", "yhat", "yhat_lower", "yhat_upper", "model_type"]
        )

    avail_pred_models = sorted(source_preds["model_type"].astype(str).unique())
    eff_weights = weights
    if (
        isinstance(weights, Mapping)
        and len(weights) == 1
        and not isinstance(next(iter(weights.values())), Mapping)
        and str(next(iter(weights.keys()))) not in avail_pred_models
        and avail_pred_models
    ):
        only_key = str(next(iter(weights.keys())))
        base_prefix = only_key.split("@", 1)[0]
        matched_m = [
            m for m in avail_pred_models if m == base_prefix or m.startswith(f"{base_prefix}_")
        ]
        base_m = (
            matched_m
            or [m for m in avail_pred_models if not m.startswith("ensemble_")]
            or avail_pred_models
        )
        eff_weights = {m: 1.0 / len(base_m) for m in base_m}

    blended_preds = _blend_frame_with_series_weights(
        source_preds,
        eff_weights,
        date_col=date_col,
        simplex_sum=self.simplex_sum,
        hierarchy_spec=self.hierarchy_spec,
    )
    if blended_preds.empty:
        return pd.DataFrame(
            columns=["ts_id", "forecast_date", "yhat", "yhat_lower", "yhat_upper", "model_type"]
        )

    # Compute empirical 80th percentile absolute residual per series on OOF
    oof_date_col = "ds" if "ds" in self.oof_df.columns else "forecast_date"
    blended_oof = _blend_frame_with_series_weights(
        self.oof_df,
        weights,
        date_col=oof_date_col,
        simplex_sum=self.simplex_sum,
        hierarchy_spec=self.hierarchy_spec,
    )
    q80_by_ts: dict[str, float] = {}
    if not blended_oof.empty and "y_true" in blended_oof.columns:
        for tid, grp_o in blended_oof.groupby("ts_id", sort=False):
            abs_res = np.abs(
                pd.to_numeric(grp_o["y_true"], errors="coerce").to_numpy(dtype=float)
                - pd.to_numeric(grp_o["yhat_blend"], errors="coerce").to_numpy(dtype=float)
            )
            finite_res = abs_res[np.isfinite(abs_res)]
            if len(finite_res) > 0:
                q80_by_ts[str(tid)] = float(np.quantile(finite_res, 0.80))

    out_rows: list[dict[str, Any]] = []
    for _, row in blended_preds.iterrows():
        tid_s = str(row["ts_id"])
        yh_val = float(row["yhat_blend"])
        q80 = q80_by_ts.get(tid_s, max(1e-3, 0.10 * abs(yh_val)))
        low_val = (
            float(row["yhat_lower_blend"])
            if "yhat_lower_blend" in row and pd.notna(row["yhat_lower_blend"])
            else (yh_val - q80)
        )
        high_val = (
            float(row["yhat_upper_blend"])
            if "yhat_upper_blend" in row and pd.notna(row["yhat_upper_blend"])
            else (yh_val + q80)
        )
        # Enforce conformal coverage floor from OOF residuals
        half_w = max(0.5 * abs(high_val - low_val), q80)
        out_rows.append(
            {
                "ts_id": tid_s,
                "forecast_date": row[date_col],
                "yhat": yh_val,
                "yhat_lower": yh_val - half_w,
                "yhat_upper": yh_val + half_w,
                "model_type": model_label,
            }
        )
    out_df = pd.DataFrame(out_rows)
    if self.hierarchy_spec is not None and not out_df.empty:
        out_df = _project_blended_hierarchy(
            out_df,
            self.hierarchy_spec,
            date_col="forecast_date",
            value_col="yhat",
        )
    if self.simplex_sum is not None and float(self.simplex_sum) > 0.0 and not out_df.empty:
        out_df = enforce_simplex_closure(
            out_df,
            value_col="yhat",
            simplex_sum=float(self.simplex_sum),
            ts_id_col="ts_id",
            date_col="forecast_date",
        )
    return out_df

EvolveConfig dataclass

EvolveConfig(
    target="features",
    backend="alphaevolve",
    tier="deep_sky",
    where="local",
    horizon=None,
    max_evaluations=10,
    significance_alpha=0.1,
    worst_decile_floor=-0.02,
    project_id=None,
    location="global",
    region="us-central1",
    model_name=DEFAULT_GEMINI_MODEL,
    export_path=None,
    random_seed=42,
    decision_metric=None,
    timeout_seconds=20.0,
    dry_run=False,
    mock_candidates=None,
    candidate_programs=None,
    lockdown_override_score=None,
    from_runs=None,
    from_run_ids=None,
    dataset_id="scale_forecasting",
)

Configuration for an opt-in :func:run_evolution / :meth:Forecaster.evolve session.

model_dump

model_dump(**_kwargs)

Pydantic-compatible alias for :meth:to_dict.

Source code in src/scale_forecasting/evolve/runner.py
def model_dump(self, **_kwargs: Any) -> dict[str, Any]:
    """Pydantic-compatible alias for :meth:`to_dict`."""
    return self.to_dict()

model_validate classmethod

model_validate(obj)

Validate a dictionary or :class:EvolveConfig instance.

Source code in src/scale_forecasting/evolve/runner.py
@classmethod
def model_validate(cls, obj: EvolveConfig | Mapping[str, Any]) -> EvolveConfig:
    """Validate a dictionary or :class:`EvolveConfig` instance."""
    if isinstance(obj, cls):
        return obj
    if isinstance(obj, Mapping):
        valid_keys = {f.name for f in dataclasses.fields(cls)}
        filtered = {k: v for k, v in obj.items() if k in valid_keys}
        if (
            "candidates" in obj
            and "mock_candidates" not in filtered
            and obj["candidates"] is not None
        ):
            filtered["mock_candidates"] = tuple(obj["candidates"])
        return cls(**filtered)
    raise ConfigError(f"Cannot coerce {type(obj).__name__} into EvolveConfig.")

to_dict

to_dict()

Serialize configuration to a plain JSON-friendly dictionary.

Source code in src/scale_forecasting/evolve/runner.py
def to_dict(self) -> dict[str, Any]:
    """Serialize configuration to a plain JSON-friendly dictionary."""
    raw = dataclasses.asdict(self)
    if raw.get("mock_candidates") is not None:
        raw["mock_candidates"] = list(raw["mock_candidates"])
    if raw.get("from_runs") is not None:
        raw["from_runs"] = list(raw["from_runs"])
    if raw.get("from_run_ids") is not None:
        raw["from_run_ids"] = list(raw["from_run_ids"])
    return raw

EvolveResult dataclass

EvolveResult(
    target,
    backend_used,
    promoted,
    rejection_reason,
    baseline_score,
    inner_cv_score,
    lockdown_baseline_score,
    lockdown_candidate_score,
    fva_pct,
    dm_pvalue,
    worst_decile_fva_pct,
    champion_code,
    export_path,
    leaderboard_df,
    forecaster=None,
    assessment=None,
    evaluations_run=0,
    wall_seconds=0.0,
    candidate_code="",
    diagnostics=dict(),
    predictions_df=None,
    model_name=DEFAULT_GEMINI_MODEL,
)

Outcome of an evolutionary run governed by the 3-Gate Anti-Overfitting Ratchet.

emit_airflow_dag

emit_airflow_dag(
    output_path=None, schedule="@monthly", *, dag_id=None
)

Render a standalone Cloud Composer 3 / Airflow DAG scheduling periodic evolution.

If output_path is provided, writes the DAG Python source to output_path and returns the rendered DAG source code string.

Source code in src/scale_forecasting/evolve/runner.py
    def emit_airflow_dag(
        self,
        output_path: str | Path | None = None,
        schedule: str = "@monthly",
        *,
        dag_id: str | None = None,
    ) -> str:
        """Render a standalone Cloud Composer 3 / Airflow DAG scheduling periodic evolution.

        If ``output_path`` is provided, writes the DAG Python source to ``output_path`` and returns
        the rendered DAG source code string.
        """
        import tempfile

        eff_dag_id = dag_id or f"scale_forecasting_evolve_{self.target}"
        default_export = Path(tempfile.gettempdir()) / f"evolved_{self.target}.py"
        export_target = self.export_path or str(default_export)
        dag_source = f'''"""Airflow DAG for scheduled scale_forecasting.evolve ({self.target})."""

from __future__ import annotations

from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash import BashOperator

DEFAULT_ARGS = {{
    "owner": "scale-forecasting",
    "depends_on_past": False,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
}}

with DAG(
    dag_id="{eff_dag_id}",
    default_args=DEFAULT_ARGS,
    description=(
        "Scheduled 3-Gate Anti-Overfitting evolution for "
        "target={self.target} (backend={self.backend_used}, model={self.model_name})"
    ),
    schedule="{schedule}",
    start_date=datetime(2026, 1, 1),
    catchup=False,
    tags=["scale-forecasting", "evolve", "{self.target}", "{self.backend_used}"],
) as dag:
    evolve_and_verify = BashOperator(
        task_id="evolve_{self.target}_with_3gate_ratchet",
        bash_command=(
            "python -m scale_forecasting.evolve "
            "--target {self.target} "
            "--backend {self.backend_used} "
            "--model-name {self.model_name} "
            "--export-path {export_target}"
        ),
    )
'''
        if output_path is not None:
            out_p = Path(output_path)
            out_p.parent.mkdir(parents=True, exist_ok=True)
            out_p.write_text(dag_source, encoding="utf-8")
        return dag_source

summary

summary()

Return a concise human-readable summary of the 3-Gate Ratchet verdict.

Source code in src/scale_forecasting/evolve/runner.py
def summary(self) -> str:
    """Return a concise human-readable summary of the 3-Gate Ratchet verdict."""
    verdict = (
        "PROMOTED (Passed Gates 1, 2 & 3)"
        if self.promoted
        else f"RATCHETED TO BASELINE ({self.rejection_reason})"
    )
    return (
        f"EvolveResult(target='{self.target}', backend='{self.backend_used}', "
        f"verdict='{verdict}', baseline={self.baseline_score:.4f}, "
        f"inner_cv={self.inner_cv_score:.4f}, "
        f"lockdown_base={self.lockdown_baseline_score:.4f}, "
        f"lockdown_cand={self.lockdown_candidate_score:.4f}, "
        f"fva_pct={self.fva_pct:+.2f}%, dm_pvalue={self.dm_pvalue:.4f}, "
        f"worst_decile_fva={self.worst_decile_fva_pct:+.4f}, "
        f"wall_s={self.wall_seconds:.2f}s)"
    )

to_dict

to_dict()

Serialize result summary and leaderboard to a JSON-compatible dictionary.

Source code in src/scale_forecasting/evolve/runner.py
def to_dict(self) -> dict[str, Any]:
    """Serialize result summary and leaderboard to a JSON-compatible dictionary."""
    return {
        "target": self.target,
        "backend_used": self.backend_used,
        "model_name": self.model_name,
        "promoted": self.promoted,
        "rejection_reason": self.rejection_reason,
        "baseline_score": (
            round(self.baseline_score, 6) if math.isfinite(self.baseline_score) else None
        ),
        "inner_cv_score": (
            round(self.inner_cv_score, 6) if math.isfinite(self.inner_cv_score) else None
        ),
        "lockdown_baseline_score": (
            round(self.lockdown_baseline_score, 6)
            if math.isfinite(self.lockdown_baseline_score)
            else None
        ),
        "lockdown_candidate_score": (
            round(self.lockdown_candidate_score, 6)
            if math.isfinite(self.lockdown_candidate_score)
            else None
        ),
        "fva_pct": round(self.fva_pct, 4) if math.isfinite(self.fva_pct) else 0.0,
        "dm_pvalue": round(self.dm_pvalue, 6) if math.isfinite(self.dm_pvalue) else None,
        "worst_decile_fva_pct": (
            round(self.worst_decile_fva_pct, 4)
            if math.isfinite(self.worst_decile_fva_pct)
            else None
        ),
        "evaluations_run": self.evaluations_run,
        "wall_seconds": round(self.wall_seconds, 3),
        "export_path": self.export_path,
        "champion_code": self.champion_code,
        "diagnostics": self.diagnostics,
        "leaderboard": self.leaderboard_df.to_dict(orient="records"),
    }

EvolvedForecaster

EvolvedForecaster(params, ctx)

Bases: BaseModel

Custom evolutionary forecaster plugin (target='model').

Source code in src/scale_forecasting/evolve/targets.py
def __init__(self, params: dict[str, Any], ctx: ModelContext) -> None:
    super().__init__(params, ctx)
    self._last_ds: pd.Timestamp | None = None
    self._fitted_values: np.ndarray = np.array([], dtype=float)
    self._y_train: np.ndarray = np.array([], dtype=float)
    self._season_period: int = 7
    self._seasonal_profile: np.ndarray = np.zeros(7, dtype=float)
    self._level: float = 0.0
    self._slope: float = 0.0
    self._exog_cols: list[str] = []
    self._exog_coef: np.ndarray = np.array([], dtype=float)
    self._exog_mean: np.ndarray = np.array([], dtype=float)

fit

fit(y, X=None)

Fit evolutionary damped trend + harmonic seasonal + ridge exogenous model.

Source code in src/scale_forecasting/evolve/targets.py
def fit(self, y: pd.Series, X: pd.DataFrame | None = None) -> None:
    """Fit evolutionary damped trend + harmonic seasonal + ridge exogenous model."""
    y_vals = pd.to_numeric(y, errors="coerce").ffill().bfill().fillna(0.0).to_numpy(dtype=float)
    self._y_train = y_vals
    if isinstance(y.index, pd.DatetimeIndex) and len(y.index) > 0:
        self._last_ds = pd.Timestamp(y.index[-1])
    elif X is not None and "ds" in X.columns and len(X) > 0:
        self._last_ds = pd.Timestamp(X["ds"].iloc[-1])
    else:
        self._last_ds = pd.Timestamp("2025-01-01")
    self._last_date = self._last_ds

    n = len(y_vals)
    if n == 0:
        self._fitted_values = np.zeros(1, dtype=float)
        self._set_residuals(np.zeros(1, dtype=float))
        return

    # EVOLVE-BLOCK-START
    freq_str = str(self.ctx.freq).upper()
    if freq_str.startswith("M"):
        period = 12
    elif freq_str.startswith("W"):
        period = 13
    elif freq_str.startswith("Q"):
        period = 4
    elif freq_str.startswith("H"):
        period = 24
    else:
        period = 7
    self._season_period = max(1, min(period, max(1, n // 2)))

    t = np.arange(n, dtype=float)
    if n >= 4:
        t_mean = float(np.mean(t))
        y_mean = float(np.mean(y_vals))
        denom = float(np.dot(t - t_mean, t - t_mean)) + 1e-6
        raw_slope = float(np.dot(t - t_mean, y_vals - y_mean)) / denom
        self._slope = 0.85 * raw_slope
        trend_line = y_mean + raw_slope * (t - t_mean)
        self._level = float(trend_line[-1])
    else:
        self._slope = 0.0
        self._level = float(np.mean(y_vals))
        trend_line = np.full(n, self._level, dtype=float)

    detrended = y_vals - trend_line
    s_prof = np.zeros(self._season_period, dtype=float)
    for rem in range(self._season_period):
        vals_rem = detrended[rem :: self._season_period]
        if len(vals_rem) > 0:
            s_prof[rem] = float(np.median(vals_rem))
    s_prof -= float(np.mean(s_prof))
    self._seasonal_profile = s_prof

    seasonal_comp = np.array(
        [s_prof[i % self._season_period] for i in range(n)],
        dtype=float,
    )
    resid = detrended - seasonal_comp
    self._exog_cols = []
    self._exog_coef = np.array([], dtype=float)
    self._exog_mean = np.array([], dtype=float)
    exog_fit = np.zeros(n, dtype=float)
    if X is not None and not X.empty:
        num_cols = [
            c
            for c in X.columns
            if c not in ("ds", "ts_id", "y") and pd.api.types.is_numeric_dtype(X[c])
        ]
        if num_cols:
            self._exog_cols = num_cols
            x_mat = (
                X[num_cols]
                .apply(pd.to_numeric, errors="coerce")
                .fillna(0.0)
                .to_numpy(dtype=float)
            )
            self._exog_mean = np.mean(x_mat, axis=0)
            x_c = x_mat - self._exog_mean
            gram = x_c.T @ x_c + 1.0 * np.eye(len(num_cols))
            self._exog_coef = np.linalg.solve(gram, x_c.T @ resid)
            exog_fit = x_c @ self._exog_coef

    self._fitted_values = trend_line + seasonal_comp + exog_fit
    # EVOLVE-BLOCK-END
    self._set_residuals(self._y_train - self._fitted_values)

predict

predict(horizon, X=None, quantiles=DEFAULT_QUANTILES)

Predict horizon steps ahead with calibrated residual intervals.

Source code in src/scale_forecasting/evolve/targets.py
def predict(
    self,
    horizon: int,
    X: pd.DataFrame | None = None,
    quantiles: tuple[float, ...] = DEFAULT_QUANTILES,
) -> pd.DataFrame:
    """Predict ``horizon`` steps ahead with calibrated residual intervals."""
    h = int(horizon)
    n = len(self._y_train)
    if X is not None and "ds" in X.columns and len(X) >= h:
        ds = pd.DatetimeIndex(pd.to_datetime(X["ds"].iloc[:h]))
    else:
        start = self._last_ds if self._last_ds is not None else pd.Timestamp("2025-01-01")
        freq = self.ctx.freq or "D"
        ds = pd.date_range(start=start, periods=h + 1, freq=freq)[1:]

    # EVOLVE-BLOCK-START
    steps = np.arange(1, h + 1, dtype=float)
    damping = (1.0 - np.power(0.90, steps)) / (1.0 - 0.90)
    base_level = (
        float(self._fitted_values[-1] - self._seasonal_profile[(n - 1) % self._season_period])
        if n > 0 and len(self._seasonal_profile) > 0
        else self._level
    )
    seasonal_fut = np.array(
        [
            self._seasonal_profile[(n + step - 1) % self._season_period]
            for step in range(1, h + 1)
        ],
        dtype=float,
    )
    yhat_raw = base_level + self._slope * damping + seasonal_fut

    if self._exog_cols and X is not None and not X.empty:
        present = [c for c in self._exog_cols if c in X.columns]
        if len(present) == len(self._exog_cols):
            x_fut = (
                X[self._exog_cols]
                .iloc[:h]
                .apply(pd.to_numeric, errors="coerce")
                .fillna(0.0)
                .to_numpy(dtype=float)
            )
            if len(x_fut) == h:
                yhat_raw = yhat_raw + (x_fut - self._exog_mean) @ self._exog_coef
    # EVOLVE-BLOCK-END

    qmap = self.residual_intervals(yhat_raw, quantiles=tuple(quantiles))
    return self._assemble_frame(ds, qmap, raw=yhat_raw)

IslandCandidate dataclass

IslandCandidate(
    program_id,
    code,
    score,
    island_id,
    generation,
    diagnostics=dict(),
)

One evaluated candidate program stored inside :class:IslandPopulationBuffer.

IslandPopulationBuffer

IslandPopulationBuffer(n_islands=3, max_per_island=8)

In-memory multi-island MAP-Elites population buffer for backend='vertex_gemini'.

Source code in src/scale_forecasting/evolve/client.py
def __init__(self, n_islands: int = 3, max_per_island: int = 8) -> None:
    self.n_islands = max(1, int(n_islands))
    self.max_per_island = max(2, int(max_per_island))
    self._islands: dict[int, list[IslandCandidate]] = {i: [] for i in range(self.n_islands)}

add

add(
    program_id,
    code,
    score,
    diagnostics=None,
    *,
    generation=0,
)

Insert an evaluated candidate into its corresponding island and prune low performers.

Source code in src/scale_forecasting/evolve/client.py
def add(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
    *,
    generation: int = 0,
) -> None:
    """Insert an evaluated candidate into its corresponding island and prune low performers."""
    if not math.isfinite(score):
        return
    island_id = int(generation) % self.n_islands
    cand = IslandCandidate(
        program_id=program_id,
        code=code,
        score=float(score),
        island_id=island_id,
        generation=int(generation),
        diagnostics=dict(diagnostics or {}),
    )
    bucket = self._islands[island_id]
    bucket.append(cand)
    bucket.sort(key=lambda c: c.score)
    if len(bucket) > self.max_per_island:
        del bucket[self.max_per_island :]

best

best()

Return the global best candidate across all islands.

Source code in src/scale_forecasting/evolve/client.py
def best(self) -> IslandCandidate | None:
    """Return the global best candidate across all islands."""
    all_cands = [c for b in self._islands.values() for c in b]
    return min(all_cands, key=lambda c: c.score) if all_cands else None

select_parent

select_parent(generation)

Select the lowest-loss parent from the active island for generation.

Source code in src/scale_forecasting/evolve/client.py
def select_parent(self, generation: int) -> IslandCandidate | None:
    """Select the lowest-loss parent from the active island for ``generation``."""
    island_id = int(generation) % self.n_islands
    bucket = self._islands.get(island_id, [])
    if bucket:
        return bucket[0]
    all_cands = [c for b in self._islands.values() for c in b]
    if not all_cands:
        return None
    return min(all_cands, key=lambda c: c.score)

MockEvolutionClient

MockEvolutionClient(
    target="features",
    candidates=None,
    max_evaluations=10,
    *,
    model_name=DEFAULT_GEMINI_MODEL,
)

Offline deterministic evolution transport for fast unit testing and CI --dry-run.

Source code in src/scale_forecasting/evolve/client.py
def __init__(
    self,
    target: str = "features",
    candidates: Sequence[str] | None = None,
    max_evaluations: int = 10,
    *,
    model_name: str = DEFAULT_GEMINI_MODEL,
) -> None:
    self.target = target
    self.model_name = model_name
    self._custom_candidates = list(candidates) if candidates is not None else None
    self.max_evaluations = max(1, int(max_evaluations))
    self.recorded_evaluations: list[dict[str, Any]] = []

propose_candidate

propose_candidate(
    target, parent_code, diagnostics=None, generation=1
)

Return deterministic candidate generation - 1 with zero network calls.

Source code in src/scale_forecasting/evolve/client.py
def propose_candidate(
    self,
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Return deterministic candidate ``generation - 1`` with zero network calls."""
    _ = (parent_code, diagnostics)
    spec = get_target_seed(target)
    if self._custom_candidates:
        raw = self._custom_candidates[(generation - 1) % len(self._custom_candidates)]
        if "def " in raw or "class " in raw:
            return raw
        return inject_evolve_block(spec.seed_code, raw)
    built_in = deterministic_mock_candidates(spec.target, count=max(3, self.max_evaluations))
    return built_in[(generation - 1) % len(built_in)]

record_evaluation

record_evaluation(
    program_id,
    code,
    score,
    diagnostics=None,
    *,
    generation=1,
)

Append evaluation telemetry to self.recorded_evaluations.

Source code in src/scale_forecasting/evolve/client.py
def record_evaluation(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
    *,
    generation: int = 1,
) -> None:
    """Append evaluation telemetry to ``self.recorded_evaluations``."""
    self.recorded_evaluations.append(
        {
            "program_id": program_id,
            "code": code,
            "score": float(score) if math.isfinite(score) else None,
            "generation": generation,
            "diagnostics": dict(diagnostics or {}),
        }
    )

SandboxValidationResult dataclass

SandboxValidationResult(
    valid, violations=(), ast_node_count=0
)

Result of static AST security inspection on a candidate program.

errors property

errors

Alias for self.violations.

is_valid property

is_valid

Alias for self.valid.

reason property

reason

Joined violation summary string, or None when valid.

TargetSpec dataclass

TargetSpec(
    target,
    entrypoint,
    description,
    seed_code,
    system_instruction,
    mutation_prompt_template,
)

Specification and seed program for one # EVOLVE-BLOCK evolutionary target.

VertexGeminiEvolutionClient

VertexGeminiEvolutionClient(
    project_id=None,
    region="us-central1",
    model_name=DEFAULT_GEMINI_MODEL,
    *,
    n_islands=3,
    temperature=0.4,
    genai_client=None,
)

Backup non-default evolution transport using standard Vertex AI Gemini.

Uses google.genai.Client(vertexai=True, project=project_id, location=region) (default model "gemini-3.8-flash", or any caller-supplied model_name) plus :class:IslandPopulationBuffer to mutate # EVOLVE-BLOCK code from walk-forward diagnostic feedback without requiring a Gemini Enterprise license.

Source code in src/scale_forecasting/evolve/client.py
def __init__(
    self,
    project_id: str | None = None,
    region: str = "us-central1",
    model_name: str = DEFAULT_GEMINI_MODEL,
    *,
    n_islands: int = 3,
    temperature: float = 0.4,
    genai_client: Any = None,
) -> None:
    self.project_id = (
        _resolve_project_id(project_id)
        if genai_client is None
        else (project_id or os.environ.get("SF_PROJECT_ID") or "mock-project")
    )
    self.region = region
    self.model_name = model_name
    self.temperature = temperature
    self.population = IslandPopulationBuffer(n_islands=n_islands)
    self._genai_client = genai_client
    self._custom_genai_client = genai_client is not None

propose_candidate

propose_candidate(
    target, parent_code, diagnostics=None, generation=1
)

Mutate # EVOLVE-BLOCK using Vertex AI Gemini + island population state.

Source code in src/scale_forecasting/evolve/client.py
def propose_candidate(
    self,
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Mutate ``# EVOLVE-BLOCK`` using Vertex AI Gemini + island population state."""
    spec = get_target_seed(target)
    island_parent = self.population.select_parent(generation)
    eff_parent = island_parent.code if island_parent is not None else parent_code
    eff_diag = (
        island_parent.diagnostics
        if (island_parent is not None and island_parent.diagnostics)
        else dict(diagnostics or {})
    )
    prompt = build_mutation_prompt(
        target=spec.target,
        parent_code=eff_parent,
        diagnostics=eff_diag,
        generation=generation,
    )
    raw_response = self._generate_text(spec.system_instruction, prompt)
    if not raw_response.strip():
        # Fallback to deterministic candidate if model response is empty
        cands = deterministic_mock_candidates(spec.target, count=max(1, generation))
        return cands[(generation - 1) % len(cands)]
    try:
        injected = inject_evolve_block(spec.seed_code, raw_response)
        if validate_candidate_ast(injected).valid:
            return injected
    except Exception as exc:  # noqa: BLE001 - malformed LLM block falls back cleanly
        _log.debug("Vertex Gemini candidate block failed AST validation: %s", exc)
    cands = deterministic_mock_candidates(spec.target, count=max(1, generation))
    return cands[(generation - 1) % len(cands)]

record_evaluation

record_evaluation(
    program_id,
    code,
    score,
    diagnostics=None,
    *,
    generation=1,
)

Record candidate score and walk-forward diagnostics into the island buffer.

Source code in src/scale_forecasting/evolve/client.py
def record_evaluation(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
    *,
    generation: int = 1,
) -> None:
    """Record candidate score and walk-forward diagnostics into the island buffer."""
    self.population.add(
        program_id=program_id,
        code=code,
        score=score,
        diagnostics=diagnostics,
        generation=generation,
    )

build_mutation_prompt

build_mutation_prompt(
    target, parent_code, diagnostics=None, generation=1
)

Render a diagnostic-guided mutation prompt for target.

Source code in src/scale_forecasting/evolve/targets.py
def build_mutation_prompt(
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Render a diagnostic-guided mutation prompt for ``target``."""
    spec = get_target_seed(target)
    diag_dict = dict(diagnostics or {})
    diag_summary = (
        f"fva_pct={diag_dict.get('fva_pct', 0.0):.2f}%, "
        f"dm_pvalue={diag_dict.get('dm_pvalue', 1.0):.4f}, "
        f"worst_decile_fva={diag_dict.get('worst_decile_fva', 0.0):.4f}, "
        f"horizon_decay={diag_dict.get('horizon_decay', 'stable')}, "
        f"inner_cv_score={diag_dict.get('inner_cv_score', 'n/a')}, "
        f"baseline_score={diag_dict.get('baseline_score', 'n/a')}, "
        f"monotonic_constraints={diag_dict.get('monotonic_constraints', {})}, "
        f"is_compositional_simplex={diag_dict.get('is_compositional_simplex', False)}, "
        f"simplex_total={diag_dict.get('simplex_total')}, "
        f"hierarchy_id_cols={diag_dict.get('hierarchy_id_cols', [])}, "
        f"reconcile_temporal={diag_dict.get('reconcile_temporal', False)}, "
        f"has_cold_start={diag_dict.get('has_cold_start', False)}, "
        f"cold_start_fraction={diag_dict.get('cold_start_fraction', 0.0)}, "
        f"cold_start_donor_similarity={diag_dict.get('cold_start_donor_similarity', 0.0)}, "
        f"calibration_method={diag_dict.get('calibration_method', 'conformal')}, "
        f"residual_drift_ks_stat={diag_dict.get('residual_drift_ks_stat', 0.0)}, "
        f"cross_series_residual_corr={diag_dict.get('cross_series_residual_corr', 0.0)}"
    )
    return spec.mutation_prompt_template.format(
        generation=generation,
        diagnostics=diag_summary,
        parent_code=parent_code.strip(),
    )

compile_candidate_symbol

compile_candidate_symbol(code, entrypoint)

Validate code with :func:validate_candidate_ast and return entrypoint.

Source code in src/scale_forecasting/evolve/sandbox.py
def compile_candidate_symbol(code: str, entrypoint: str) -> Any:
    """Validate ``code`` with :func:`validate_candidate_ast` and return ``entrypoint``."""
    validation = validate_candidate_ast(code)
    if not validation.valid:
        raise ConfigError(f"Candidate failed AST security sandbox: {validation.reason}")

    env: dict[str, Any] = {
        "__builtins__": dict(_SAFE_BUILTINS),
        "np": np,
        "numpy": np,
        "pd": pd,
        "pandas": pd,
        "math": math,
        "statistics": statistics,
        "scipy": scipy,
        "stats": scipy_stats,
        "BaseModel": BaseModel,
        "ModelContext": ModelContext,
        "DEFAULT_QUANTILES": DEFAULT_QUANTILES,
        "AutoPolicyWeights": AutoPolicyWeights,
    }
    compiled = compile(code, filename="<evolve_candidate>", mode="exec")
    exec(compiled, env)
    if entrypoint not in env:
        raise ConfigError(f"Candidate code did not define required entrypoint '{entrypoint}'.")
    return env[entrypoint]

compute_evolved_similarity_kernel

compute_evolved_similarity_kernel(
    features_mat, profile=None
)

Synthesize an (N, N) similarity matrix in [0.0, 1.0] over per-series embeddings.

Source code in src/scale_forecasting/evolve/targets.py
def compute_evolved_similarity_kernel(
    features_mat: np.ndarray,
    profile: dict[str, Any] | None = None,
) -> np.ndarray:
    """Synthesize an ``(N, N)`` similarity matrix in ``[0.0, 1.0]`` over per-series embeddings."""
    _ = profile
    x_raw = np.asarray(features_mat, dtype=float)
    if x_raw.ndim == 1:
        x_raw = x_raw.reshape(-1, 1)
    n_series = int(x_raw.shape[0])
    if n_series <= 1:
        return np.ones((max(1, n_series), max(1, n_series)), dtype=float)
    x_clean = np.nan_to_num(x_raw, nan=0.0, posinf=0.0, neginf=0.0)
    col_mean = np.mean(x_clean, axis=0, keepdims=True)
    col_std = np.where(
        np.std(x_clean, axis=0, keepdims=True) > 1e-8, np.std(x_clean, axis=0, keepdims=True), 1.0
    )
    x_norm = (x_clean - col_mean) / col_std

    # EVOLVE-BLOCK-START
    norms = np.linalg.norm(x_norm, axis=1, keepdims=True)
    norms = np.where(norms > 1e-8, norms, 1.0)
    unit_x = x_norm / norms
    cos_sim = np.clip(unit_x @ unit_x.T, -1.0, 1.0)
    sq_dists = np.sum((x_norm[:, None, :] - x_norm[None, :, :]) ** 2, axis=-1)
    med_sq = float(np.median(sq_dists)) if sq_dists.size > 0 else 1.0
    rbf_sim = np.exp(-sq_dists / max(1e-6, 2.0 * med_sq))
    sim_matrix = 0.55 * np.maximum(0.0, cos_sim) + 0.45 * rbf_sim
    # EVOLVE-BLOCK-END

    sim_out = np.asarray(sim_matrix, dtype=float)
    sim_out = np.nan_to_num(sim_out, nan=0.0, posinf=1.0, neginf=0.0)
    sim_out = 0.5 * (sim_out + sim_out.T)
    sim_out = np.clip(sim_out, 0.0, 1.0)
    np.fill_diagonal(sim_out, 1.0)
    return sim_out

compute_evolved_weights

compute_evolved_weights(oof_df, profile=None)

Compute global (dict[str, float]) or per-series (dict[str, dict[str, float]]) weights.

Source code in src/scale_forecasting/evolve/targets.py
def compute_evolved_weights(
    oof_df: pd.DataFrame,
    profile: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Compute global (`dict[str, float]`) or per-series (`dict[str, dict[str, float]]`) weights."""
    _ = profile
    if oof_df.empty or "model_type" not in oof_df.columns:
        return {}
    work = oof_df.copy()
    date_col = (
        "ds"
        if "ds" in work.columns
        else ("forecast_date" if "forecast_date" in work.columns else "")
    )
    per_series_weights: dict[str, dict[str, float]] = {}

    # EVOLVE-BLOCK-START
    scores: dict[str, float] = {}
    for model_type, grp in work.groupby("model_type", sort=False):
        y_true = pd.to_numeric(grp["y_true"], errors="coerce").to_numpy(dtype=float)
        yhat = pd.to_numeric(grp["yhat"], errors="coerce").to_numpy(dtype=float)
        mask = np.isfinite(y_true) & np.isfinite(yhat)
        if not mask.any():
            continue
        abs_err = np.abs(y_true[mask] - yhat[mask])
        denom = max(1e-6, float(np.sum(np.abs(y_true[mask]))))
        wape = float(np.sum(abs_err)) / denom
        scores[str(model_type)] = 1.0 / max(1e-6, wape**2)
    # EVOLVE-BLOCK-END

    if per_series_weights:
        return per_series_weights

    total = sum(v for v in scores.values() if math.isfinite(v) and v > 0.0)
    if total <= 0.0:
        models = sorted(work["model_type"].astype(str).unique())
        global_w = {m: 1.0 / len(models) for m in models} if models else {}
    else:
        global_w = {k: float(v) / total for k, v in scores.items() if math.isfinite(v) and v > 0.0}

    if "ts_id" not in work.columns or not date_col or work["ts_id"].nunique() < 2 or not global_w:
        return global_w

    # Fold-consistent per-series adaptive shrinkage around the global champion
    model_mean_wape: dict[str, float] = {}
    for m_name, grp_m in work.groupby("model_type", sort=False):
        s_losses: list[float] = []
        for _, grp_s in grp_m.groupby("ts_id", sort=False):
            yt_s = pd.to_numeric(grp_s["y_true"], errors="coerce").to_numpy(dtype=float)
            yh_s = pd.to_numeric(grp_s["yhat"], errors="coerce").to_numpy(dtype=float)
            mk = np.isfinite(yt_s) & np.isfinite(yh_s)
            if mk.any():
                s_losses.append(
                    float(np.sum(np.abs(yt_s[mk] - yh_s[mk])))
                    / max(1e-6, float(np.sum(np.abs(yt_s[mk]))))
                )
        if s_losses:
            model_mean_wape[str(m_name)] = float(np.mean(s_losses))
    champ_m = (
        min(model_mean_wape, key=lambda k: model_mean_wape[k])
        if model_mean_wape
        else max(global_w, key=lambda k: global_w[k])
    )

    adaptive_map: dict[str, dict[str, float]] = {}
    for tid, grp_t in work.groupby("ts_id", sort=True):
        piv = grp_t.pivot_table(
            index=date_col, columns="model_type", values="yhat", aggfunc="first"
        ).sort_index()
        yt = pd.to_numeric(
            grp_t.groupby(date_col)["y_true"].first().reindex(piv.index), errors="coerce"
        ).to_numpy(dtype=float)
        if champ_m not in piv.columns or len(yt) < 2:
            adaptive_map[str(tid)] = dict(global_w)
            continue
        yc = pd.to_numeric(piv[champ_m], errors="coerce").to_numpy(dtype=float)
        base_err = np.abs(yt - yc)
        mid = max(1, len(yt) // 2)
        best_w: dict[str, float] = {champ_m: 1.0}
        best_loss = float(np.sum(base_err))

        # Test global_w blend on this series
        yg = np.zeros_like(yt)
        wg_sum = 0.0
        for m_k, w_k in global_w.items():
            if m_k in piv.columns:
                ym_k = pd.to_numeric(piv[m_k], errors="coerce").to_numpy(dtype=float)
                if np.isfinite(ym_k).all():
                    yg = yg + w_k * ym_k
                    wg_sum += w_k
        if wg_sum > 1e-9:
            yg = yg / wg_sum
            err_g = np.abs(yt - yg)
            if (
                float(np.sum(err_g)) < best_loss - 1e-6
                and float(np.sum(err_g[:mid])) <= float(np.sum(base_err[:mid]))
                and float(np.sum(err_g[mid:])) <= float(np.sum(base_err[mid:]))
                and float(np.mean(err_g <= base_err)) >= 0.55
            ):
                best_loss = float(np.sum(err_g))
                best_w = {m_k: w_k / wg_sum for m_k, w_k in global_w.items() if m_k in piv.columns}

        # Test fold-consistent pairwise blends with global champion
        for m_col in piv.columns:
            m_str = str(m_col)
            if m_str == champ_m:
                continue
            ym = pd.to_numeric(piv[m_col], errors="coerce").to_numpy(dtype=float)
            if not np.isfinite(ym).all():
                continue
            for alpha in (-0.08, 0.15, 0.25, 0.35, 0.50, 0.65, 0.80):
                y_blend = (1.0 - alpha) * yc + alpha * ym
                err_b = np.abs(yt - y_blend)
                if (
                    float(np.sum(err_b)) < best_loss - 1e-6
                    and float(np.sum(err_b[:mid])) <= float(np.sum(base_err[:mid]))
                    and float(np.sum(err_b[mid:])) <= float(np.sum(base_err[mid:]))
                    and float(np.mean(err_b <= base_err)) >= 0.55
                ):
                    best_loss = float(np.sum(err_b))
                    best_w = {champ_m: round(1.0 - alpha, 4), m_str: round(alpha, 4)}
        adaptive_map[str(tid)] = best_w
    return adaptive_map

create_evolution_client

create_evolution_client(
    backend,
    *,
    target="features",
    project_id=None,
    location="global",
    region="us-central1",
    model_name=DEFAULT_GEMINI_MODEL,
    max_evaluations=10,
    mock_candidates=None,
    genai_client=None,
    alphaevolve_http_request=None,
)

Instantiate the requested evolution client backend.

Source code in src/scale_forecasting/evolve/client.py
def create_evolution_client(
    backend: str,
    *,
    target: str = "features",
    project_id: str | None = None,
    location: str = "global",
    region: str = "us-central1",
    model_name: str = DEFAULT_GEMINI_MODEL,
    max_evaluations: int = 10,
    mock_candidates: Sequence[str] | None = None,
    genai_client: Any = None,
    alphaevolve_http_request: Callable[..., dict[str, Any]] | None = None,
) -> AlphaEvolveClient | VertexGeminiEvolutionClient | MockEvolutionClient:
    """Instantiate the requested evolution client backend."""
    norm = str(backend).strip().lower()
    if norm == "alphaevolve":
        return AlphaEvolveClient(
            project_id=project_id,
            location=location,
            model_name=model_name,
            http_request=alphaevolve_http_request,
        )
    if norm == "vertex_gemini":
        return VertexGeminiEvolutionClient(
            project_id=project_id,
            region=region,
            model_name=model_name,
            genai_client=genai_client,
        )
    if norm == "mock":
        return MockEvolutionClient(
            target=target,
            candidates=mock_candidates,
            max_evaluations=max_evaluations,
            model_name=model_name,
        )
    raise ConfigurationError(
        f"Unknown evolution backend '{backend}'. Valid backends: "
        "'alphaevolve', 'vertex_gemini', 'mock'."
    )

deterministic_mock_candidates

deterministic_mock_candidates(target, count=3)

Return count deterministic, AST-safe, causal candidate programs for target.

Source code in src/scale_forecasting/evolve/targets.py
def deterministic_mock_candidates(target: str, count: int = 3) -> list[str]:
    """Return ``count`` deterministic, AST-safe, causal candidate programs for ``target``."""
    spec = get_target_seed(target)
    blocks_by_target: dict[str, tuple[str, ...]] = {
        "features": _MOCK_FEATURES_BLOCKS,
        "ensemble": _MOCK_ENSEMBLE_BLOCKS,
        "model": _MOCK_MODEL_BLOCKS,
        "policy": _MOCK_POLICY_BLOCKS,
        "similarity_kernel": _MOCK_SIMILARITY_KERNEL_BLOCKS,
    }
    blocks = blocks_by_target[spec.target]
    candidates: list[str] = []
    for idx in range(max(1, count)):
        blk = blocks[idx % len(blocks)]
        candidates.append(inject_evolve_block(spec.seed_code, blk))
    return candidates

evolve_policy_weights

evolve_policy_weights(base_weights)

Tune :class:AutoPolicyWeights thresholds for auto_policy (target='policy').

Source code in src/scale_forecasting/evolve/targets.py
def evolve_policy_weights(base_weights: AutoPolicyWeights) -> AutoPolicyWeights:
    """Tune :class:`AutoPolicyWeights` thresholds for ``auto_policy`` (`target='policy'`)."""
    # EVOLVE-BLOCK-START
    updated_actions = dict(base_weights.action_weights)
    updated_actions["prune_decoy_covariates"] = (0.90, 7.5)
    updated_actions["inject_transform_log1p"] = (0.93, 10.8)
    updated_actions["inject_direct_horizon_models"] = (0.86, 6.2)
    updated_actions["inject_monotone_guardrails"] = (0.88, 7.0)
    updated_actions["inject_transform_simplex"] = (0.89, 8.4)
    updated_actions["enable_temporal_reconciliation"] = (0.81, 5.2)
    updated_actions["enable_cold_start_transfer"] = (0.86, 6.8)
    updated_actions["enable_adaptive_conformal"] = (0.83, 5.4)
    return base_weights.with_updates(
        intermittent_share_min=0.16,
        log1p_level_vol_corr_min=0.60,
        log1p_growth_ratio_min=1.30,
        direct_horizon_decay_ratio_min=1.28,
        pass_decay_factor=0.74,
        action_weights=updated_actions,
    )

execute_in_sandbox

execute_in_sandbox(
    code, entrypoint, *args, timeout_seconds=10.0, **kwargs
)

Compile and execute entrypoint(*args, **kwargs) with a hard wall-clock timeout.

Source code in src/scale_forecasting/evolve/sandbox.py
def execute_in_sandbox(
    code: str,
    entrypoint: str,
    *args: Any,
    timeout_seconds: float = 10.0,
    **kwargs: Any,
) -> Any:
    """Compile and execute ``entrypoint(*args, **kwargs)`` with a hard wall-clock timeout."""
    symbol = compile_candidate_symbol(code, entrypoint)
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
        future = pool.submit(symbol, *args, **kwargs)
        try:
            return future.result(timeout=max(0.5, float(timeout_seconds)))
        except concurrent.futures.TimeoutError as exc:
            raise TimeoutError(
                f"Candidate '{entrypoint}' exceeded sandbox timeout ({timeout_seconds:.1f}s)."
            ) from exc

extract_evolve_block

extract_evolve_block(code)

Extract the code lines between # EVOLVE-BLOCK-START and # EVOLVE-BLOCK-END.

If the markers are absent from code, returns normalized dedented code.

Source code in src/scale_forecasting/evolve/targets.py
def extract_evolve_block(code: str) -> str:
    """Extract the code lines between ``# EVOLVE-BLOCK-START`` and ``# EVOLVE-BLOCK-END``.

    If the markers are absent from ``code``, returns normalized dedented ``code``.
    """
    text = str(code)
    start_idx = text.find(EVOLVE_BLOCK_START)
    end_idx = text.find(EVOLVE_BLOCK_END)
    if start_idx == -1 or end_idx == -1 or end_idx < start_idx:
        return _normalize_block_indent(text)
    inner = text[start_idx + len(EVOLVE_BLOCK_START) : end_idx]
    return _normalize_block_indent(inner)

get_target_seed

get_target_seed(target)

Return the canonical :class:TargetSpec for target.

Source code in src/scale_forecasting/evolve/targets.py
def get_target_seed(target: str) -> TargetSpec:
    """Return the canonical :class:`TargetSpec` for ``target``."""
    norm = str(target).strip().lower()
    if norm not in _TARGET_SPECS:
        valid = ", ".join(EVOLVE_TARGETS)
        raise ConfigError(f"Unknown evolve target '{target}'. Valid targets: {valid}")
    return _TARGET_SPECS[norm]

inject_evolve_block

inject_evolve_block(template, block)

Inject block between # EVOLVE-BLOCK-START and # EVOLVE-BLOCK-END in template.

Handles both: - an inner snippet (indented to match # EVOLVE-BLOCK-START in template), and - a full program that already contains # EVOLVE-BLOCK-START / # EVOLVE-BLOCK-END (its inner block is extracted first and injected into template).

Source code in src/scale_forecasting/evolve/targets.py
def inject_evolve_block(template: str, block: str) -> str:
    """Inject ``block`` between ``# EVOLVE-BLOCK-START`` and ``# EVOLVE-BLOCK-END`` in ``template``.

    Handles both:
    - an inner snippet (indented to match ``# EVOLVE-BLOCK-START`` in ``template``), and
    - a full program that already contains ``# EVOLVE-BLOCK-START`` / ``# EVOLVE-BLOCK-END`` (its
      inner block is extracted first and injected into ``template``).
    """
    clean_block = str(block).strip("\r\n")
    fence_match = re.search(r"```(?:python)?[ \t]*\r?\n(.*?)```", clean_block, flags=re.DOTALL)
    if fence_match:
        clean_block = fence_match.group(1).strip("\r\n")

    if EVOLVE_BLOCK_START in clean_block and EVOLVE_BLOCK_END in clean_block:
        clean_block = extract_evolve_block(clean_block)

    if EVOLVE_BLOCK_START not in template or EVOLVE_BLOCK_END not in template:
        raise ConfigError(f"Template is missing {EVOLVE_BLOCK_START} / {EVOLVE_BLOCK_END} markers.")

    lines = template.splitlines()
    out_lines: list[str] = []
    in_block = False
    injected = False
    for line in lines:
        if EVOLVE_BLOCK_START in line and not injected:
            indent = line[: len(line) - len(line.lstrip())]
            out_lines.append(line)
            dedented = _normalize_block_indent(clean_block)
            for b_line in dedented.splitlines():
                out_lines.append(f"{indent}{b_line}" if b_line.strip() else "")
            in_block = True
            injected = True
            continue
        if EVOLVE_BLOCK_END in line and in_block:
            in_block = False
            out_lines.append(line)
            continue
        if not in_block:
            out_lines.append(line)

    return "\n".join(out_lines) + "\n"

main

main(argv=None)

CLI entry point wrapper delegating to :func:scale_forecasting.evolve.__main__.main.

Source code in src/scale_forecasting/evolve/__init__.py
def main(argv: list[str] | None = None) -> int:
    """CLI entry point wrapper delegating to :func:`scale_forecasting.evolve.__main__.main`."""
    from .__main__ import main as _cli_main

    return _cli_main(argv)

probe_alphaevolve_access

probe_alphaevolve_access(
    project_id=None,
    location="global",
    *,
    timeout=10.0,
    http_get=None,
)

Fast pre-flight check verifying Discovery Engine AlphaEvolve entitlement before backtests.

Raises :class:~scale_forecasting.errors.ConfigError (aliased as ConfigurationError) if discoveryengine.googleapis.com is disabled or the project/organization lacks Gemini Enterprise AlphaEvolve entitlement (HTTP 403 / 404).

Source code in src/scale_forecasting/evolve/client.py
def probe_alphaevolve_access(
    project_id: str | None = None,
    location: str = "global",
    *,
    timeout: float = 10.0,
    http_get: Callable[..., Any] | None = None,
) -> dict[str, Any]:
    """Fast pre-flight check verifying Discovery Engine AlphaEvolve entitlement before backtests.

    Raises :class:`~scale_forecasting.errors.ConfigError` (aliased as ``ConfigurationError``) if
    ``discoveryengine.googleapis.com`` is disabled or the project/organization lacks Gemini
    Enterprise AlphaEvolve entitlement (``HTTP 403`` / ``404``).
    """
    resolved_project = _resolve_project_id(project_id)
    base_url = ALPHAEVOLVE_BASE_URL_TEMPLATE.format(
        project_id=resolved_project,
        location=location,
    )
    probe_url = f"{base_url}?pageSize=1"

    if http_get is not None:
        try:
            resp = http_get(probe_url, timeout=timeout)
        except urllib.error.HTTPError as exc:
            body_text = ""
            try:
                body_text = exc.read().decode("utf-8", errors="replace")
            except Exception:  # noqa: BLE001 - best-effort error body decode
                body_text = str(exc)
            raise ConfigurationError(
                _format_alphaevolve_entitlement_error(
                    resolved_project, location, exc.code, body_text
                )
            ) from exc
        except ConfigError:
            raise
        except Exception as exc:
            raise ConfigurationError(
                _format_alphaevolve_entitlement_error(resolved_project, location, "ERROR", str(exc))
            ) from exc

        if isinstance(resp, Mapping):
            status = int(resp.get("status", 200))
            if status in (401, 403, 404) or status >= 400:
                raise ConfigurationError(
                    _format_alphaevolve_entitlement_error(
                        resolved_project,
                        location,
                        status,
                        str(resp.get("error", resp.get("body", ""))),
                    )
                )
            return {
                "accessible": True,
                "backend": "alphaevolve",
                "project_id": resolved_project,
                "location": location,
                "endpoint": base_url,
                "response": dict(resp),
            }
        status_attr = getattr(resp, "status", getattr(resp, "status_code", 200))
        if int(status_attr) >= 400:
            raise ConfigurationError(
                _format_alphaevolve_entitlement_error(resolved_project, location, int(status_attr))
            )
        return {
            "accessible": True,
            "backend": "alphaevolve",
            "project_id": resolved_project,
            "location": location,
            "endpoint": base_url,
        }

    token = _get_adc_bearer_token(resolved_project)
    req = urllib.request.Request(
        probe_url,
        headers={
            "Authorization": f"Bearer {token}",
            "x-goog-user-project": resolved_project,
            "Content-Type": "application/json",
        },
        method="GET",
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as response:
            raw_body = response.read().decode("utf-8", errors="replace")
            parsed = json.loads(raw_body) if raw_body.strip().startswith("{") else {}
            return {
                "accessible": True,
                "backend": "alphaevolve",
                "project_id": resolved_project,
                "location": location,
                "endpoint": base_url,
                "response": parsed,
            }
    except urllib.error.HTTPError as exc:
        body_text = ""
        try:
            body_text = exc.read().decode("utf-8", errors="replace")
        except Exception:  # noqa: BLE001 - best-effort error body read
            body_text = str(exc)
        raise ConfigurationError(
            _format_alphaevolve_entitlement_error(resolved_project, location, exc.code, body_text)
        ) from exc
    except Exception as exc:
        raise ConfigurationError(
            _format_alphaevolve_entitlement_error(
                resolved_project, location, "UNREACHABLE", str(exc)
            )
        ) from exc

run_evolution

run_evolution(
    data=None,
    config=None,
    *,
    from_runs=None,
    from_run_ids=None,
    dataset_id=None,
    target=None,
    backend=None,
    tier=None,
    where=None,
    horizon=None,
    max_evaluations=None,
    significance_alpha=None,
    worst_decile_floor=None,
    project_id=None,
    location=None,
    region=None,
    model_name=None,
    export_path=None,
    random_seed=None,
    decision_metric=None,
    timeout_seconds=None,
    dry_run=None,
    mock_candidates=None,
    candidates=None,
    lockdown_override_score=None,
    genai_client=None,
    alphaevolve_http_request=None,
    http_get=None,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    freq=None,
)

Run opt-in evolutionary code synthesis on top of Forecaster.auto() or prior runs.

Source code in src/scale_forecasting/evolve/runner.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
def run_evolution(
    data: pd.DataFrame | str | Any | None = None,
    config: EvolveConfig | Mapping[str, Any] | None = None,
    *,
    from_runs: Sequence[Any] | None = None,
    from_run_ids: Sequence[str] | None = None,
    dataset_id: str | None = None,
    target: str | None = None,
    backend: str | None = None,
    tier: str | None = None,
    where: str | None = None,
    horizon: int | None = None,
    max_evaluations: int | None = None,
    significance_alpha: float | None = None,
    worst_decile_floor: float | None = None,
    project_id: str | None = None,
    location: str | None = None,
    region: str | None = None,
    model_name: str | None = None,
    export_path: str | Path | None = None,
    random_seed: int | None = None,
    decision_metric: str | None = None,
    timeout_seconds: float | None = None,
    dry_run: bool | None = None,
    mock_candidates: Sequence[str] | None = None,
    candidates: Sequence[str] | None = None,
    lockdown_override_score: float | None = None,
    genai_client: Any = None,
    alphaevolve_http_request: Callable[..., dict[str, Any]] | None = None,
    http_get: Callable[..., Any] | None = None,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    freq: str | None = None,
) -> EvolveResult:
    """Run opt-in evolutionary code synthesis on top of ``Forecaster.auto()`` or prior runs."""
    t_start = time.monotonic()
    base_dict: dict[str, Any] = {}
    if config is not None:
        base_dict = EvolveConfig.model_validate(config).to_dict()

    # When evolving directly on prior runs or an executed Forecaster without an explicit target,
    # default to "ensemble" (post-run pool evolution without base-model refitting).
    has_post_run_inputs = (
        from_runs is not None
        or from_run_ids is not None
        or bool(base_dict.get("from_runs"))
        or bool(base_dict.get("from_run_ids"))
        or (data is not None and not isinstance(data, (pd.DataFrame, str)))
    )
    if (
        has_post_run_inputs
        and target is None
        and config is None
        and base_dict.get("target") is None
    ):
        target = "ensemble"

    eff_candidates = mock_candidates if mock_candidates is not None else candidates
    overrides: dict[str, Any] = {
        "target": target,
        "backend": backend,
        "tier": tier,
        "where": where,
        "horizon": horizon,
        "max_evaluations": max_evaluations,
        "significance_alpha": significance_alpha,
        "worst_decile_floor": worst_decile_floor,
        "project_id": project_id,
        "location": location,
        "region": region,
        "model_name": model_name,
        "export_path": str(export_path) if export_path is not None else None,
        "random_seed": random_seed,
        "decision_metric": decision_metric,
        "timeout_seconds": timeout_seconds,
        "dry_run": dry_run,
        "mock_candidates": tuple(eff_candidates) if eff_candidates is not None else None,
        "lockdown_override_score": lockdown_override_score,
        "from_runs": tuple(from_runs) if from_runs is not None else None,
        "from_run_ids": tuple(str(r) for r in from_run_ids) if from_run_ids is not None else None,
        "dataset_id": dataset_id,
    }
    for k, v in overrides.items():
        if v is not None:
            base_dict[k] = v

    cfg = EvolveConfig.model_validate(base_dict)
    spec = get_target_seed(cfg.target)

    # Fast offline dry-run path (validates AST + temporal causality in <0.1s)
    if cfg.dry_run:
        ast_check = validate_candidate_ast(spec.seed_code)
        sample_df = pd.DataFrame(
            {
                "ts_id": ["s0"] * 16,
                "ds": pd.date_range("2025-01-01", periods=16, freq="D"),
                "y": [float(i + (i % 4)) for i in range(16)],
                "promo": [float(i % 2) for i in range(16)],
            }
        )
        causal_check = verify_no_future_leakage(synthesize_evolved_features, sample_df, horizon=4)
        dry_lb = pd.DataFrame(
            [
                {
                    "candidate_id": f"seed_{cfg.target}_dry_run",
                    "generation": 0,
                    "target": cfg.target,
                    "backend": cfg.backend,
                    "ast_valid": ast_check.valid,
                    "causal_valid": causal_check,
                    "inner_cv_score": 0.10,
                    "baseline_score": 0.10,
                    "inner_fva_pct": 0.0,
                    "dm_pvalue": 1.0,
                    "worst_decile_fva_pct": 0.0,
                    "gate1_passed": False,
                    "gate2_passed": False,
                    "lockdown_baseline_score": 0.10,
                    "lockdown_candidate_score": 0.10,
                    "gate3_passed": False,
                    "promoted": False,
                    "status": "dry_run",
                    "rejection_reason": "dry_run: offline pre-flight validation only",
                    "wall_seconds": round(time.monotonic() - t_start, 4),
                }
            ]
        )
        if cfg.export_path:
            out_p = Path(cfg.export_path)
            out_p.parent.mkdir(parents=True, exist_ok=True)
            out_p.write_text(spec.seed_code, encoding="utf-8")
        return EvolveResult(
            target=cfg.target,
            backend_used=cfg.backend,
            promoted=False,
            rejection_reason="dry_run: offline pre-flight validation only",
            baseline_score=0.10,
            inner_cv_score=0.10,
            lockdown_baseline_score=0.10,
            lockdown_candidate_score=0.10,
            fva_pct=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=0.0,
            champion_code=spec.seed_code,
            export_path=cfg.export_path,
            leaderboard_df=dry_lb,
            forecaster=None,
            assessment=None,
            evaluations_run=0,
            wall_seconds=time.monotonic() - t_start,
            candidate_code=spec.seed_code,
            diagnostics={
                "dry_run": True,
                "model_name": cfg.model_name,
                "ast_valid": ast_check.valid,
                "causal_valid": causal_check,
            },
            model_name=cfg.model_name,
        )

    # Pre-flight access probe for backend="alphaevolve" BEFORE running any backtests
    if cfg.backend == "alphaevolve" and alphaevolve_http_request is None:
        probe_alphaevolve_access(
            project_id=cfg.project_id,
            location=cfg.location,
            http_get=http_get,
        )

    is_post_run_call = (
        bool(cfg.from_runs)
        or bool(cfg.from_run_ids)
        or (data is not None and not isinstance(data, (pd.DataFrame, str)))
    )
    panel_df: Any = None if is_post_run_call else _resolve_input_dataframe(data)
    if data is not None and not isinstance(data, (pd.DataFrame, str)) and not cfg.from_runs:
        panel_df = data

    client = create_evolution_client(
        cfg.backend,
        target=cfg.target,
        project_id=cfg.project_id,
        location=cfg.location,
        region=cfg.region,
        model_name=cfg.model_name,
        max_evaluations=cfg.max_evaluations,
        mock_candidates=cfg.mock_candidates,
        genai_client=genai_client,
        alphaevolve_http_request=alphaevolve_http_request,
    )

    evaluator = EvolutionEvaluator(
        panel_df,
        from_runs=cfg.from_runs,
        from_run_ids=cfg.from_run_ids,
        dataset_id=cfg.dataset_id,
        project_id=cfg.project_id,
        region=cfg.region,
        target=cfg.target,
        backend=cfg.backend,
        tier=cfg.tier,
        where=cfg.where,
        horizon=cfg.horizon,
        significance_alpha=cfg.significance_alpha,
        worst_decile_floor=cfg.worst_decile_floor,
        timeout_seconds=cfg.timeout_seconds,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        freq=freq,
    )

    prof_dict = evaluator.profile_dict
    f_cfg = getattr(evaluator.forecaster, "config", None)
    f_feats = getattr(f_cfg, "features", None) if f_cfg is not None else None
    f_hier = getattr(f_cfg, "hierarchy", None) if f_cfg is not None else None
    mono_constraints: dict[str, Any] = (
        dict(getattr(f_feats, "monotonic_constraints", {}) or {}) if f_feats is not None else {}
    )
    if not mono_constraints and isinstance(prof_dict.get("monotonic_constraints"), Mapping):
        mono_constraints = dict(prof_dict["monotonic_constraints"])
    simplex_total = (
        prof_dict.get("simplex_total")
        if prof_dict.get("simplex_total") is not None
        else (getattr(f_feats, "simplex_sum", None) if f_feats is not None else None)
    )
    is_simplex = bool(prof_dict.get("is_compositional_simplex", False) or simplex_total is not None)
    hier_cols = list(
        prof_dict.get("hierarchy_id_cols")
        or (getattr(f_hier, "levels", []) if f_hier is not None else [])
    )
    rec_temporal = bool(
        prof_dict.get("reconcile_temporal", False)
        or (
            f_hier is not None
            and (
                bool(getattr(f_hier, "reconcile_temporal", False))
                or bool(getattr(f_hier, "cross_temporal", False))
            )
        )
    )
    f_cal = getattr(f_cfg, "calibration", None) if f_cfg is not None else None
    regime_shares_dict = dict(prof_dict.get("regime_shares") or {})
    cs_frac = float(
        prof_dict.get(
            "cold_start_fraction",
            regime_shares_dict.get("cold_start", 0.0),
        )
        or 0.0
    )
    has_cs = bool(
        prof_dict.get("has_cold_start", False)
        or cs_frac > 0.0
        or (getattr(f_feats, "cold_start_transfer", False) if f_feats is not None else False)
    )
    structural_diag: dict[str, Any] = {
        "monotonic_constraints": mono_constraints,
        "is_compositional_simplex": is_simplex,
        "simplex_total": simplex_total,
        "hierarchy_id_cols": hier_cols,
        "reconcile_temporal": rec_temporal,
        "has_cold_start": has_cs,
        "cold_start_fraction": cs_frac,
        "cold_start_donor_similarity": float(prof_dict.get("cold_start_donor_similarity", 0.0)),
        "calibration_method": str(
            prof_dict.get(
                "calibration_method",
                getattr(f_cal, "method", "conformal") if f_cal is not None else "conformal",
            )
        ),
        "residual_drift_ks_stat": float(prof_dict.get("residual_drift_ks_stat", 0.0)),
        "cross_series_residual_corr": float(
            prof_dict.get("cross_series_residual_corr", prof_dict.get("cross_series_corr", 0.0))
        ),
    }

    evaluations: list[CandidateEvaluation] = []
    current_parent_code = spec.seed_code
    last_diag: dict[str, Any] = {
        "fva_pct": 0.0,
        "dm_pvalue": 1.0,
        "worst_decile_fva": 0.0,
        "horizon_decay": "baseline",
        "baseline_score": evaluator.baseline_score,
        "inner_cv_score": evaluator.baseline_score,
        **structural_diag,
    }

    for gen in range(1, cfg.max_evaluations + 1):
        cand_code = client.propose_candidate(
            target=cfg.target,
            parent_code=current_parent_code,
            diagnostics=last_diag,
            generation=gen,
        )
        cand_eval = evaluator.evaluate_candidate_inner(cand_code, generation=gen)
        evaluations.append(cand_eval)

        cand_diag = {
            "fva_pct": cand_eval.inner_fva_pct,
            "dm_pvalue": cand_eval.dm_pvalue,
            "worst_decile_fva": cand_eval.worst_decile_fva_pct,
            "horizon_decay": "improved" if cand_eval.gate1_passed else "degraded",
            "baseline_score": cand_eval.baseline_score,
            "inner_cv_score": cand_eval.inner_cv_score,
            **structural_diag,
        }
        client.record_evaluation(
            program_id=cand_eval.candidate_id,
            code=cand_code,
            score=cand_eval.inner_cv_score,
            diagnostics=cand_diag,
        )
        if cand_eval.gate1_passed and math.isfinite(cand_eval.inner_cv_score):
            current_parent_code = cand_code
            last_diag = cand_diag

    # Select best inner-CV candidate (preferring candidates that passed both Gate 1 and Gate 2)
    gate12_winners = [e for e in evaluations if e.gate1_passed and e.gate2_passed]
    gate1_winners = [e for e in evaluations if e.gate1_passed]
    if gate12_winners:
        best_idx = min(
            range(len(evaluations)),
            key=lambda i: (
                evaluations[i].inner_cv_score
                if (evaluations[i].gate1_passed and evaluations[i].gate2_passed)
                else float("inf")
            ),
        )
    elif gate1_winners:
        best_idx = min(
            range(len(evaluations)),
            key=lambda i: (
                evaluations[i].inner_cv_score if evaluations[i].gate1_passed else float("inf")
            ),
        )
    else:
        best_idx = min(range(len(evaluations)), key=lambda i: evaluations[i].inner_cv_score)

    best_inner = evaluations[best_idx]
    final_eval = evaluator.evaluate_lockdown_gate3(best_inner)

    if cfg.lockdown_override_score is not None:
        forced_lock = float(cfg.lockdown_override_score)
        forced_g3 = bool(forced_lock < evaluator.lockdown_baseline_score - 1e-9)
        forced_promoted = bool(final_eval.gate1_passed and final_eval.gate2_passed and forced_g3)
        forced_reason = (
            None
            if forced_promoted
            else (
                f"Gate 3 (Held-Out Lockdown Fold): candidate improved inner CV "
                f"({final_eval.inner_cv_score:.4f} < {final_eval.baseline_score:.4f}) "
                f"but degraded on the unseen lockdown fold "
                f"({forced_lock:.4f} >= {evaluator.lockdown_baseline_score:.4f}). "
                f"Ratcheted back to Forecaster.auto() baseline."
            )
        )
        final_eval = CandidateEvaluation(
            **{
                **final_eval.__dict__,
                "lockdown_candidate_score": forced_lock,
                "gate3_passed": forced_g3,
                "promoted": forced_promoted,
                "status": "promoted_champion" if forced_promoted else "rejected_gate3",
                "rejection_reason": forced_reason,
            }
        )

    evaluations[best_idx] = final_eval
    leaderboard_df = pd.DataFrame([e.to_row() for e in evaluations])

    champion_code = final_eval.code if final_eval.promoted else spec.seed_code
    if cfg.export_path is not None:
        out_p = Path(cfg.export_path)
        out_p.parent.mkdir(parents=True, exist_ok=True)
        out_p.write_text(champion_code, encoding="utf-8")

    assessment_df = (
        evaluator.session.practitioner_assessment_df()
        if evaluator.session is not None
        else pd.DataFrame()
    )
    fva_pct = final_eval.inner_fva_pct
    if (
        final_eval.promoted
        and math.isfinite(final_eval.lockdown_baseline_score)
        and final_eval.lockdown_baseline_score > 1e-9
    ):
        lock_fva = (
            100.0
            * (final_eval.lockdown_baseline_score - final_eval.lockdown_candidate_score)
            / final_eval.lockdown_baseline_score
        )
        fva_pct = max(fva_pct, lock_fva)

    materialized_preds_df: pd.DataFrame | None = None
    if cfg.target == "ensemble":
        try:
            if final_eval.promoted:
                champ_fn = compile_candidate_symbol(champion_code, spec.entrypoint)
                champ_weights = champ_fn(evaluator.oof_df.copy(), evaluator.profile_dict)
                materialized_preds_df = evaluator.materialize_ensemble_predictions(
                    champ_weights, model_label="ensemble_evolved"
                )
            else:
                reigning = evaluator.reigning_champion_model or "ensemble_mean"
                materialized_preds_df = evaluator.materialize_ensemble_predictions(
                    {reigning: 1.0}, model_label=reigning
                )
        except Exception:  # noqa: BLE001 - best-effort forward prediction materialization
            materialized_preds_df = None

    merged_diagnostics: dict[str, Any] = {
        **evaluator.pool_diagnostics,
        "model_name": cfg.model_name,
        "reigning_champion_model": evaluator.reigning_champion_model,
        "gate1_passed": final_eval.gate1_passed,
        "gate2_passed": final_eval.gate2_passed,
        "gate3_passed": final_eval.gate3_passed,
        "status": final_eval.status,
    }

    return EvolveResult(
        target=cfg.target,
        backend_used=cfg.backend,
        promoted=final_eval.promoted,
        rejection_reason=final_eval.rejection_reason,
        baseline_score=evaluator.baseline_score,
        inner_cv_score=final_eval.inner_cv_score,
        lockdown_baseline_score=evaluator.lockdown_baseline_score,
        lockdown_candidate_score=final_eval.lockdown_candidate_score,
        fva_pct=round(float(fva_pct), 4),
        dm_pvalue=round(float(final_eval.dm_pvalue), 6)
        if math.isfinite(final_eval.dm_pvalue)
        else 1.0,
        worst_decile_fva_pct=round(float(final_eval.worst_decile_fva_pct), 4),
        champion_code=champion_code,
        export_path=cfg.export_path,
        leaderboard_df=leaderboard_df,
        forecaster=evaluator.forecaster,
        assessment=assessment_df,
        evaluations_run=len(evaluations),
        wall_seconds=time.monotonic() - t_start,
        candidate_code=final_eval.code,
        diagnostics=merged_diagnostics,
        predictions_df=materialized_preds_df,
        model_name=cfg.model_name,
    )

split_inner_and_lockdown_panel

split_inner_and_lockdown_panel(
    df,
    horizon,
    *,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
)

Split a historical panel into (inner_df, lockdown_truth_df, lockdown_future_exog_df).

  • inner_df: rows $t \le T - H_{\text{lockdown}}$ per series (visible to evolution).
  • lockdown_truth_df: last $H_{\text{lockdown}}$ historical rows per series with true y (withheld for Gate 3 verification).
  • lockdown_future_exog_df: exogenous covariate rows for the lockdown window with y removed so lockdown predictions cannot observe held-out targets.
Source code in src/scale_forecasting/evolve/evaluator.py
def split_inner_and_lockdown_panel(
    df: pd.DataFrame,
    horizon: int,
    *,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    """Split a historical panel into `(inner_df, lockdown_truth_df, lockdown_future_exog_df)`.

    - ``inner_df``: rows $t \\le T - H_{\\text{lockdown}}$ per series (visible to evolution).
    - ``lockdown_truth_df``: last $H_{\\text{lockdown}}$ historical rows per series with true
      ``y`` (withheld for Gate 3 verification).
    - ``lockdown_future_exog_df``: exogenous covariate rows for the lockdown window with ``y``
      removed so lockdown predictions cannot observe held-out targets.
    """
    work = df.copy()
    if ts_id_col not in work.columns:
        work[ts_id_col] = "series_0"
    y_num = pd.to_numeric(work[target_col], errors="coerce")
    hist = work[y_num.notna()].sort_values([ts_id_col, date_col]).reset_index(drop=True)
    if hist.empty:
        raise ConfigError("Input panel has no valid numeric target rows.")

    h = max(1, int(horizon))
    inner_parts: list[pd.DataFrame] = []
    lock_parts: list[pd.DataFrame] = []

    for _, grp in hist.groupby(ts_id_col, sort=False):
        n_obs = len(grp)
        eff_h = min(h, max(2, n_obs // 4))
        inner_parts.append(grp.iloc[:-eff_h])
        lock_parts.append(grp.iloc[-eff_h:])

    inner_df = pd.concat(inner_parts, ignore_index=True)
    lockdown_truth_df = pd.concat(lock_parts, ignore_index=True)
    exog_cols = [c for c in lockdown_truth_df.columns if c != target_col]
    lockdown_future_exog_df = lockdown_truth_df[exog_cols].copy()
    return inner_df, lockdown_truth_df, lockdown_future_exog_df

synthesize_evolved_features

synthesize_evolved_features(df, profile=None)

Synthesize causal evolved_feat_* columns without future target lookahead.

Source code in src/scale_forecasting/evolve/targets.py
def synthesize_evolved_features(
    df: pd.DataFrame,
    profile: dict[str, Any] | None = None,
) -> pd.DataFrame:
    """Synthesize causal ``evolved_feat_*`` columns without future target lookahead."""
    out = df.copy()
    id_col = str((profile or {}).get("ts_id_col", "ts_id"))
    if id_col not in out.columns:
        id_col = "ts_id" if "ts_id" in out.columns else out.columns[0]

    # EVOLVE-BLOCK-START
    step_idx = out.groupby(id_col, sort=False).cumcount().to_numpy(dtype=float)
    out["evolved_feat_trend_idx"] = np.log1p(step_idx)
    out["evolved_feat_sin_w"] = np.sin(2.0 * np.pi * step_idx / 7.0)
    out["evolved_feat_cos_w"] = np.cos(2.0 * np.pi * step_idx / 7.0)

    reserved = {id_col, "ts_id", "ds", "date", "forecast_date", "y", "y_true", "yhat"}
    exog_cols = [
        c
        for c in out.columns
        if c not in reserved
        and not str(c).startswith("evolved_feat_")
        and pd.api.types.is_numeric_dtype(out[c])
    ]
    for col in exog_cols[:3]:
        vals = pd.to_numeric(out[col], errors="coerce").fillna(0.0)
        out[f"evolved_feat_{col}_lag1"] = (
            vals.groupby(out[id_col], sort=False).shift(1).fillna(vals)
        )
        out[f"evolved_feat_{col}_roll3"] = (
            vals.groupby(out[id_col], sort=False)
            .transform(lambda s: s.rolling(3, min_periods=1).mean())
            .astype(float)
        )
    # EVOLVE-BLOCK-END
    return out

validate_candidate_ast

validate_candidate_ast(code)

Parse code into an AST and reject prohibited imports, calls, and reflection.

Source code in src/scale_forecasting/evolve/sandbox.py
def validate_candidate_ast(code: str) -> SandboxValidationResult:
    """Parse ``code`` into an AST and reject prohibited imports, calls, and reflection."""
    if not isinstance(code, str) or not code.strip():
        return SandboxValidationResult(
            valid=False,
            violations=("Candidate code is empty.",),
            ast_node_count=0,
        )

    try:
        tree = ast.parse(code)
    except SyntaxError as exc:
        return SandboxValidationResult(
            valid=False,
            violations=(f"SyntaxError at line {exc.lineno}: {exc.msg}",),
            ast_node_count=0,
        )

    violations: list[str] = []
    node_count = 0

    for node in ast.walk(tree):
        node_count += 1
        if node_count > _MAX_AST_NODES:
            violations.append(f"AST node count exceeds maximum limit ({_MAX_AST_NODES}).")
            break

        if isinstance(node, ast.Import):
            for alias in node.names:
                root_mod = alias.name.split(".", 1)[0]
                if root_mod in PROHIBITED_MODULES:
                    violations.append(f"Prohibited import '{alias.name}'.")
                elif root_mod not in ALLOWED_MODULES:
                    violations.append(
                        f"Import '{alias.name}' is not in the allowed scientific module whitelist."
                    )

        elif isinstance(node, ast.ImportFrom):
            mod_name = node.module or ""
            root_mod = mod_name.split(".", 1)[0] if mod_name else ""
            if root_mod in PROHIBITED_MODULES:
                violations.append(f"Prohibited import from '{mod_name}'.")
            elif root_mod and root_mod not in ALLOWED_MODULES:
                violations.append(
                    f"Import from '{mod_name}' is not in the allowed scientific module whitelist."
                )
            for alias in node.names:
                if alias.name in PROHIBITED_MODULES or alias.name in PROHIBITED_CALLS:
                    violations.append(f"Prohibited symbol import '{alias.name}'.")

        elif isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                fn_name = node.func.id
                if fn_name in PROHIBITED_CALLS:
                    violations.append(f"Prohibited function call '{fn_name}()'.")
            elif isinstance(node.func, ast.Attribute):
                attr_name = node.func.attr
                if attr_name in PROHIBITED_CALLS:
                    violations.append(f"Prohibited method call '.{attr_name}()'.")
                if attr_name in (
                    "to_csv",
                    "to_parquet",
                    "to_pickle",
                    "read_csv",
                    "read_pickle",
                    "read_parquet",
                ):
                    violations.append(f"Prohibited file I/O method call '.{attr_name}()'.")

        elif isinstance(node, ast.Attribute):
            if node.attr in _PROHIBITED_DUNDER_ATTRS:
                violations.append(f"Prohibited dunder attribute access '.{node.attr}'.")

        elif isinstance(node, ast.Name) and node.id in ("__builtins__", "__import__"):
            violations.append(f"Prohibited identifier '{node.id}'.")

    return SandboxValidationResult(
        valid=(len(violations) == 0),
        violations=tuple(dict.fromkeys(violations)),
        ast_node_count=node_count,
    )

verify_no_future_leakage

verify_no_future_leakage(
    fn,
    df,
    target_col="y",
    time_col="ds",
    id_col="ts_id",
    horizon=7,
)

Verify that perturbing the last horizon target values by +1e6 does not alter any engineered features or fitted values on earlier timestamps $t \le T - H$.

Returns True only when all outputs on $t \le T - H$ are bit-for-bit identical (np.allclose(..., atol=1e-12, equal_nan=True)). Immediately returns False if the candidate uses future information (such as .shift(-k), .bfill(), or full-series global target aggregations).

Source code in src/scale_forecasting/evolve/sandbox.py
def verify_no_future_leakage(
    fn: Any,
    df: pd.DataFrame,
    target_col: str = "y",
    time_col: str = "ds",
    id_col: str = "ts_id",
    horizon: int = 7,
) -> bool:
    """Verify that perturbing the last ``horizon`` target values by ``+1e6`` does not alter
    any engineered features or fitted values on earlier timestamps $t \\le T - H$.

    Returns ``True`` only when all outputs on $t \\le T - H$ are bit-for-bit identical
    (``np.allclose(..., atol=1e-12, equal_nan=True)``). Immediately returns ``False`` if the
    candidate uses future information (such as ``.shift(-k)``, ``.bfill()``, or full-series
    global target aggregations).
    """
    if df.empty or target_col not in df.columns:
        return False

    h = max(1, int(horizon))
    work = df.copy()
    if id_col not in work.columns:
        work[id_col] = "series_0"
    if time_col in work.columns:
        work = work.sort_values([id_col, time_col]).reset_index(drop=True)
    else:
        work = work.reset_index(drop=True)

    # Handle BaseModel subclass (target="model")
    if isinstance(fn, type) and issubclass(fn, BaseModel):
        try:
            first_id = str(work[id_col].iloc[0])
            s_df = work[work[id_col].astype(str) == first_id].reset_index(drop=True)
            if len(s_df) <= h + 2:
                return True
            y_clean = pd.Series(
                pd.to_numeric(s_df[target_col], errors="coerce").to_numpy(dtype=float),
                index=pd.to_datetime(s_df[time_col]) if time_col in s_df.columns else None,
            )
            y_pert = y_clean.copy()
            y_pert.iloc[-h:] = y_pert.iloc[-h:] + 1e6

            ctx = ModelContext(freq="D", horizon=h)
            m_clean = fn({}, ctx)
            m_clean.fit(y_clean.iloc[:-h])
            m_pert = fn({}, ctx)
            m_pert.fit(y_pert.iloc[:-h])
            p_clean = m_clean.predict(h)["yhat"].to_numpy(dtype=float)
            p_pert = m_pert.predict(h)["yhat"].to_numpy(dtype=float)
            return bool(np.allclose(p_clean, p_pert, atol=1e-12, rtol=1e-9, equal_nan=True))
        except Exception:  # noqa: BLE001 - any failure inside candidate model rejects it
            return False

    # Build prefix mask (True for earlier timestamps t <= T - H, False for last H rows per series)
    prefix_mask = np.ones(len(work), dtype=bool)
    df_clean = work.copy()
    df_perturbed = work.copy()
    df_perturbed[target_col] = pd.to_numeric(df_perturbed[target_col], errors="coerce").astype(
        float
    )

    for _, grp in work.groupby(id_col, sort=False):
        idx = grp.index.to_numpy()
        eff_h = min(h, max(1, len(idx) // 2))
        tail_idx = idx[-eff_h:]
        prefix_mask[tail_idx] = False
        df_perturbed.loc[tail_idx, target_col] = (
            df_perturbed.loc[tail_idx, target_col].to_numpy(dtype=float) + 1e6
        )

    try:
        out_clean = fn(df_clean)
        out_perturbed = fn(df_perturbed)
    except TypeError:
        try:
            out_clean = fn(df_clean, None)
            out_perturbed = fn(df_perturbed, None)
        except Exception:  # noqa: BLE001 - candidate raised during causality check
            return False
    except Exception:  # noqa: BLE001 - candidate raised during causality check
        return False

    if not isinstance(out_clean, pd.DataFrame) or not isinstance(out_perturbed, pd.DataFrame):
        return False
    if len(out_clean) != len(work) or len(out_perturbed) != len(work):
        return False
    if list(out_clean.columns) != list(out_perturbed.columns):
        return False

    for col in out_clean.columns:
        if col in (id_col, time_col):
            continue
        s_clean = out_clean[col].iloc[prefix_mask]
        s_pert = out_perturbed[col].iloc[prefix_mask]
        if pd.api.types.is_numeric_dtype(s_clean) or pd.api.types.is_numeric_dtype(s_pert):
            a_clean = pd.to_numeric(s_clean, errors="coerce").to_numpy(dtype=float)
            a_pert = pd.to_numeric(s_pert, errors="coerce").to_numpy(dtype=float)
            if not np.allclose(a_clean, a_pert, atol=1e-12, rtol=1e-9, equal_nan=True):
                return False
        else:
            if not s_clean.astype(str).equals(s_pert.astype(str)):
                return False

    return True

verify_oof_pool_compatibility

verify_oof_pool_compatibility(
    runs,
    *,
    project_id=None,
    dataset_id="scale_forecasting",
    region="us-central1",
    horizon=None,
)

Verify OOF & horizon alignment across runs, disambiguate colliding models, and split.

Verifies how borrowing interacts with backtest, hpo, and ensemble: - Requires non-empty overlapping (ts_id, ds) out-of-fold rows across all runs (and overlapping (ts_id, forecast_date) horizon grids when forward predictions are present), raising :class:~scale_forecasting.errors.ConfigError when disjoint. - When multiple runs contain the same model_type, compares their aligned OOF yhat trajectories: identical trajectories (same model_spec_hash) are deduplicated, whereas distinct trajectories (different HPO winner, model_params, or ensemble pool) are disambiguated as <model_type>@<run_short_id>. - Splits the pooled oof_df temporally per series into inner_oof_df (for candidate synthesis and Gates 1 & 2) and lockdown_oof_df (withheld for Gate 3).

Source code in src/scale_forecasting/evolve/evaluator.py
def verify_oof_pool_compatibility(
    runs: Sequence[Any],
    *,
    project_id: str | None = None,
    dataset_id: str = "scale_forecasting",
    region: str = "us-central1",
    horizon: int | None = None,
) -> dict[str, Any]:
    """Verify OOF & horizon alignment across ``runs``, disambiguate colliding models, and split.

    Verifies how borrowing interacts with ``backtest``, ``hpo``, and ``ensemble``:
    - Requires non-empty overlapping ``(ts_id, ds)`` out-of-fold rows across all runs (and
      overlapping ``(ts_id, forecast_date)`` horizon grids when forward predictions are present),
      raising :class:`~scale_forecasting.errors.ConfigError` when disjoint.
    - When multiple runs contain the same ``model_type``, compares their aligned OOF ``yhat``
      trajectories: identical trajectories (same ``model_spec_hash``) are deduplicated, whereas
      distinct trajectories (different HPO winner, ``model_params``, or ensemble pool) are
      disambiguated as ``<model_type>@<run_short_id>``.
    - Splits the pooled ``oof_df`` temporally per series into ``inner_oof_df`` (for candidate
      synthesis and Gates 1 & 2) and ``lockdown_oof_df`` (withheld for Gate 3).
    """
    if not runs:
        raise ConfigError("verify_oof_pool_compatibility requires at least one run.")

    extracted = [
        _extract_run_artifacts(
            r,
            idx=i,
            project_id=project_id,
            dataset_id=dataset_id,
            region=region,
        )
        for i, r in enumerate(runs)
    ]

    # Ensure unique short_ids when multiple runs are pooled
    seen_shorts: set[str] = set()
    for i, item in enumerate(extracted):
        s_id = str(item["short_id"])
        if s_id in seen_shorts:
            s_id = f"{s_id}_{i + 1}"
            item["short_id"] = s_id
        seen_shorts.add(s_id)

    # 1. Verify overlapping (ts_id, ds) OOF keys across all runs
    series_sets = [set(item["oof_df"]["ts_id"].unique()) for item in extracted]
    common_series = sorted(set.intersection(*series_sets)) if series_sets else []
    if not common_series:
        raise ConfigError(
            "verify_oof_pool_compatibility failed: pooled runs share zero overlapping ts_id series."
        )

    oof_key_sets = [
        set(zip(item["oof_df"]["ts_id"], item["oof_df"]["ds"], strict=False)) for item in extracted
    ]
    common_oof_keys = set.intersection(*oof_key_sets) if oof_key_sets else set()
    if not common_oof_keys:
        raise ConfigError(
            "verify_oof_pool_compatibility failed: pooled runs share zero overlapping "
            "(ts_id, ds) out-of-fold timestamps."
        )

    # 2. Verify overlapping (ts_id, forecast_date) forward prediction keys when present
    non_empty_preds = [
        item["predictions_df"] for item in extracted if not item["predictions_df"].empty
    ]
    common_pred_keys: set[tuple[Any, Any]] | None = None
    if len(non_empty_preds) >= 2:
        pred_key_sets = [
            set(zip(p["ts_id"], p["forecast_date"], strict=False)) for p in non_empty_preds
        ]
        common_pred_keys = set.intersection(*pred_key_sets)
        if not common_pred_keys:
            raise ConfigError(
                "verify_oof_pool_compatibility failed: pooled runs share zero overlapping "
                "(ts_id, forecast_date) forward forecast horizon rows."
            )

    # 3. Filter each run to the common grid and disambiguate vs. deduplicate models across runs
    model_run_counts: dict[str, int] = {}
    for item in extracted:
        for m in item["oof_df"]["model_type"].unique():
            model_run_counts[str(m)] = model_run_counts.get(str(m), 0) + 1

    accepted_oof_by_model: dict[str, np.ndarray] = {}
    accepted_short_by_model: dict[str, str] = {}
    first_occurrence_frames: dict[str, tuple[pd.DataFrame, pd.DataFrame]] = {}
    deduplicated_models: list[str] = []
    disambiguated_models: list[str] = []

    pooled_oof_parts: list[pd.DataFrame] = []
    pooled_pred_parts: list[pd.DataFrame] = []

    for item in extracted:
        s_id = str(item["short_id"])
        oof_i = item["oof_df"].copy()
        oof_keys = list(zip(oof_i["ts_id"], oof_i["ds"], strict=False))
        oof_i = oof_i[[k in common_oof_keys for k in oof_keys]].copy()

        pred_i = item["predictions_df"].copy()
        if not pred_i.empty and common_pred_keys is not None:
            p_keys = list(zip(pred_i["ts_id"], pred_i["forecast_date"], strict=False))
            pred_i = pred_i[[k in common_pred_keys for k in p_keys]].copy()

        for m_name, grp_m in oof_i.groupby("model_type", sort=False):
            m_str = str(m_name)
            grp_sorted = grp_m.sort_values(["ts_id", "ds"]).reset_index(drop=True)
            yhat_vec = grp_sorted["yhat"].to_numpy(dtype=float)
            pred_m = (
                pred_i[pred_i["model_type"] == m_str].copy() if not pred_i.empty else pd.DataFrame()
            )

            if model_run_counts.get(m_str, 1) == 1:
                pooled_oof_parts.append(grp_sorted)
                if not pred_m.empty:
                    pooled_pred_parts.append(pred_m)
                continue

            if m_str not in accepted_oof_by_model:
                accepted_oof_by_model[m_str] = yhat_vec
                accepted_short_by_model[m_str] = s_id
                first_occurrence_frames[m_str] = (grp_sorted, pred_m)
                pooled_oof_parts.append(grp_sorted)
                if not pred_m.empty:
                    pooled_pred_parts.append(pred_m)
                continue

            prev_vec = accepted_oof_by_model[m_str]
            if len(prev_vec) == len(yhat_vec) and np.allclose(
                prev_vec, yhat_vec, atol=1e-6, equal_nan=True
            ):
                if m_str not in deduplicated_models:
                    deduplicated_models.append(m_str)
                continue

            # Disambiguate both the first occurrence (if not yet renamed) and this occurrence
            prev_short = accepted_short_by_model[m_str]
            first_oof, first_pred = first_occurrence_frames[m_str]
            first_new_name = f"{m_str}@{prev_short}"
            first_oof["model_type"] = first_new_name
            if not first_pred.empty:
                first_pred["model_type"] = first_new_name
            if first_new_name not in disambiguated_models:
                disambiguated_models.append(first_new_name)

            curr_new_name = f"{m_str}@{s_id}"
            grp_sorted = grp_sorted.copy()
            grp_sorted["model_type"] = curr_new_name
            pooled_oof_parts.append(grp_sorted)
            if not pred_m.empty:
                pred_m = pred_m.copy()
                pred_m["model_type"] = curr_new_name
                pooled_pred_parts.append(pred_m)
            if curr_new_name not in disambiguated_models:
                disambiguated_models.append(curr_new_name)

    pooled_oof_df = pd.concat(pooled_oof_parts, ignore_index=True)
    pooled_predictions_df = (
        pd.concat(pooled_pred_parts, ignore_index=True) if pooled_pred_parts else pd.DataFrame()
    )

    # 4. Split pooled_oof_df temporally per series into Inner Evolution OOF & Lockdown OOF
    inner_parts: list[pd.DataFrame] = []
    lock_parts: list[pd.DataFrame] = []
    inner_ts_count = 0
    lock_ts_count = 0

    for _, grp_s in pooled_oof_df.groupby("ts_id", sort=True):
        unique_ds = sorted(grp_s["ds"].unique())
        n_ds = len(unique_ds)
        if n_ds >= 3:
            default_lock = max(1, n_ds // 3)
            n_lock = min(
                default_lock,
                int(horizon) if horizon is not None else default_lock,
                n_ds - 2,
            )
            n_lock = max(1, n_lock)
            in_dates = set(unique_ds[:-n_lock])
            lk_dates = set(unique_ds[-n_lock:])
        elif n_ds == 2:
            in_dates = {unique_ds[0]}
            lk_dates = {unique_ds[1]}
        else:
            in_dates = set(unique_ds)
            lk_dates = set(unique_ds)

        inner_ts_count = max(inner_ts_count, len(in_dates))
        lock_ts_count = max(lock_ts_count, len(lk_dates))
        inner_parts.append(grp_s[grp_s["ds"].isin(in_dates)])
        lock_parts.append(grp_s[grp_s["ds"].isin(lk_dates)])

    inner_oof_df = pd.concat(inner_parts, ignore_index=True)
    lockdown_oof_df = pd.concat(lock_parts, ignore_index=True)

    # 5. Evaluate every model and built-in ensemble_* row to identify reigning_champion_model
    models_pooled = sorted(pooled_oof_df["model_type"].astype(str).unique())
    model_inner_scores: dict[str, float] = {}
    for m_name, grp_m in inner_oof_df.groupby("model_type", sort=False):
        s_losses = [
            _series_wape(
                grp_s["y_true"].to_numpy(dtype=float),
                grp_s["yhat"].to_numpy(dtype=float),
            )
            for _, grp_s in grp_m.groupby("ts_id", sort=True)
        ]
        if s_losses:
            model_inner_scores[str(m_name)] = float(np.mean(s_losses))

    reigning_champ = (
        min(model_inner_scores, key=lambda k: model_inner_scores[k])
        if model_inner_scores
        else (models_pooled[0] if models_pooled else "ensemble_mean")
    )

    source_run_ids = [str(item["run_id"]) for item in extracted]
    pool_diagnostics: dict[str, Any] = {
        "mode": "post_run_pool",
        "source_run_ids": source_run_ids,
        "models_pooled": models_pooled,
        "deduplicated_models": sorted(deduplicated_models),
        "disambiguated_models": sorted(disambiguated_models),
        "reigning_champion_model": reigning_champ,
        "reigning_champion_inner_score": round(
            float(model_inner_scores.get(reigning_champ, float("nan"))), 6
        ),
        "common_series_count": len(common_series),
        "inner_oof_timestamps": inner_ts_count,
        "inner_oof_Timestamps": inner_ts_count,
        "lockdown_oof_timestamps": lock_ts_count,
        "borrow_interactions": {
            "backtest": "requires identical (ts_id, ds) evaluation timestamps across pooled runs",
            "hpo": (
                "models with identical OOF trajectories are deduplicated; "
                "models with distinct HPO/config fits are disambiguated as <model>@<run_short_id>"
            ),
            "ensemble": "never borrowed passively; re-synthesized across all pooled models",
        },
    }

    return {
        "source_run_ids": source_run_ids,
        "pooled_oof_df": pooled_oof_df,
        "inner_oof_df": inner_oof_df,
        "lockdown_oof_df": lockdown_oof_df,
        "pooled_predictions_df": pooled_predictions_df,
        "reigning_champion_model": reigning_champ,
        "model_inner_scores": model_inner_scores,
        "pool_diagnostics": pool_diagnostics,
        "primary_forecaster": extracted[0].get("forecaster"),
    }

client

Dual-backend evolution transport (alphaevolve, vertex_gemini, mock) and pre-flight probe.

Provides three evolution client implementations behind a unified candidate-generation and feedback interface:

  1. Primary Managed Backend (backend="alphaevolve", Default): Connects to the Gemini Enterprise Discovery Engine AlphaEvolve REST API (https://discoveryengine.googleapis.com/v1alpha/projects/{project_id}/locations/{location}/alphaEvolveExperiments) using Application Default Credentials (ADC). Includes :func:probe_alphaevolve_access for fast pre-flight verification before any walk-forward backtests run, plus create_experiment, acquire_programs (:acquirePrograms), and submit_evaluations (:submitProgramsEvaluations).
  2. Backup Non-Default Backend (backend="vertex_gemini"): Uses standard Vertex AI Gemini (google.genai.Client(vertexai=True, project=project_id, location=region), default model "gemini-3.8-flash") paired with an in-memory multi-island MAP-Elites population buffer (:class:IslandPopulationBuffer) that mutates # EVOLVE-BLOCK code from walk-forward econometric feedback (fva_pct, dm_pvalue, worst_decile_fva, horizon_decay).
  3. Offline Deterministic Test Backend (backend="mock"): Replays a caller-supplied or built-in deterministic sequence of candidate programs with zero network calls so unit tests and CI --dry-run complete in <2 seconds.

AlphaEvolveClient

AlphaEvolveClient(
    project_id=None,
    location="global",
    *,
    model_name=DEFAULT_GEMINI_MODEL,
    timeout=30.0,
    http_request=None,
)

Managed Discovery Engine AlphaEvolve REST transport (backend='alphaevolve').

Source code in src/scale_forecasting/evolve/client.py
def __init__(
    self,
    project_id: str | None = None,
    location: str = "global",
    *,
    model_name: str = DEFAULT_GEMINI_MODEL,
    timeout: float = 30.0,
    http_request: Callable[..., dict[str, Any]] | None = None,
) -> None:
    self.project_id = _resolve_project_id(project_id)
    self.location = location
    self.model_name = model_name
    self.timeout = timeout
    self._http_request = http_request
    self._experiment_name: str | None = None

base_url property

base_url

Return the regional/global alphaEvolveExperiments collection URL.

acquire_programs

acquire_programs(experiment_name=None, count=1)

Acquire mutated candidate programs via :acquirePrograms.

Source code in src/scale_forecasting/evolve/client.py
def acquire_programs(
    self,
    experiment_name: str | None = None,
    count: int = 1,
) -> list[dict[str, Any]]:
    """Acquire mutated candidate programs via ``:acquirePrograms``."""
    exp = experiment_name or self._experiment_name
    if not exp:
        raise ConfigurationError(
            "create_experiment() must be called before acquire_programs()."
        )
    if exp.startswith(("http://", "https://")):
        url = f"{exp}:acquirePrograms"
    else:
        url = (
            f"https://discoveryengine.googleapis.com/v1alpha/{exp.lstrip('/')}:acquirePrograms"
        )
    resp = self._post_json(url, {"programCount": max(1, int(count))})
    programs = resp.get("programs", [])
    if isinstance(programs, list) and programs:
        return [dict(p) for p in programs if isinstance(p, Mapping)]
    return []

create_experiment

create_experiment(
    target, seed_code, system_instruction="", config=None
)

Create a managed alphaEvolveExperiments resource in Discovery Engine.

Source code in src/scale_forecasting/evolve/client.py
def create_experiment(
    self,
    target: str,
    seed_code: str,
    system_instruction: str = "",
    config: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
    """Create a managed ``alphaEvolveExperiments`` resource in Discovery Engine."""
    payload: dict[str, Any] = {
        "displayName": f"scale-forecasting-evolve-{target}",
        "target": target,
        "modelName": self.model_name,
        "seedProgram": {"code": seed_code},
        "systemInstruction": system_instruction,
    }
    if config:
        payload["experimentConfig"] = dict(config)
    resp = self._post_json(self.base_url, payload)
    exp_name = str(
        resp.get(
            "name",
            f"projects/{self.project_id}/locations/{self.location}/"
            f"alphaEvolveExperiments/exp-{target}",
        )
    )
    self._experiment_name = exp_name
    return {"name": exp_name, **resp}

probe_access

probe_access()

Run the pre-flight access probe against discoveryengine.googleapis.com.

Source code in src/scale_forecasting/evolve/client.py
def probe_access(self) -> dict[str, Any]:
    """Run the pre-flight access probe against ``discoveryengine.googleapis.com``."""
    return probe_alphaevolve_access(
        self.project_id,
        self.location,
        timeout=min(self.timeout, 10.0),
    )

propose_candidate

propose_candidate(
    target, parent_code, diagnostics=None, generation=1
)

Acquire the next candidate program from the managed AlphaEvolve experiment.

Source code in src/scale_forecasting/evolve/client.py
def propose_candidate(
    self,
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Acquire the next candidate program from the managed AlphaEvolve experiment."""
    spec = get_target_seed(target)
    if self._experiment_name is None:
        self.create_experiment(
            target=spec.target,
            seed_code=parent_code,
            system_instruction=spec.system_instruction,
        )
    programs = self.acquire_programs(self._experiment_name, count=1)
    if programs and "code" in programs[0]:
        raw_code = str(programs[0]["code"])
        try:
            injected = inject_evolve_block(spec.seed_code, raw_code)
            if validate_candidate_ast(injected).valid:
                return injected
        except Exception as exc:  # noqa: BLE001 - fallback when raw program is malformed
            _log.debug("Acquired AlphaEvolve program failed AST validation: %s", exc)
        cands = deterministic_mock_candidates(spec.target, count=max(1, generation))
        return cands[(generation - 1) % len(cands)]
    _ = (diagnostics, generation)
    return parent_code

record_evaluation

record_evaluation(
    program_id, code, score, diagnostics=None
)

Report candidate evaluation fitness back to Discovery Engine AlphaEvolve.

Source code in src/scale_forecasting/evolve/client.py
def record_evaluation(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
) -> None:
    """Report candidate evaluation fitness back to Discovery Engine AlphaEvolve."""
    if self._experiment_name is None:
        return
    self.submit_evaluations(
        self._experiment_name,
        [
            {
                "programId": program_id,
                "code": code,
                "fitnessScore": float(-score if math.isfinite(score) else -1e6),
                "metrics": dict(diagnostics or {}),
            }
        ],
    )

submit_evaluations

submit_evaluations(experiment_name=None, evaluations=())

Submit walk-forward evaluation scores via :submitProgramsEvaluations.

Source code in src/scale_forecasting/evolve/client.py
def submit_evaluations(
    self,
    experiment_name: str | None = None,
    evaluations: Sequence[Mapping[str, Any]] = (),
) -> dict[str, Any]:
    """Submit walk-forward evaluation scores via ``:submitProgramsEvaluations``."""
    exp = experiment_name or self._experiment_name
    if not exp:
        raise ConfigurationError(
            "create_experiment() must be called before submit_evaluations()."
        )
    if exp.startswith(("http://", "https://")):
        url = f"{exp}:submitProgramsEvaluations"
    else:
        url = (
            "https://discoveryengine.googleapis.com/v1alpha/"
            f"{exp.lstrip('/')}:submitProgramsEvaluations"
        )
    return self._post_json(
        url,
        {"programEvaluations": [dict(e) for e in evaluations]},
    )

IslandCandidate dataclass

IslandCandidate(
    program_id,
    code,
    score,
    island_id,
    generation,
    diagnostics=dict(),
)

One evaluated candidate program stored inside :class:IslandPopulationBuffer.

IslandPopulationBuffer

IslandPopulationBuffer(n_islands=3, max_per_island=8)

In-memory multi-island MAP-Elites population buffer for backend='vertex_gemini'.

Source code in src/scale_forecasting/evolve/client.py
def __init__(self, n_islands: int = 3, max_per_island: int = 8) -> None:
    self.n_islands = max(1, int(n_islands))
    self.max_per_island = max(2, int(max_per_island))
    self._islands: dict[int, list[IslandCandidate]] = {i: [] for i in range(self.n_islands)}

add

add(
    program_id,
    code,
    score,
    diagnostics=None,
    *,
    generation=0,
)

Insert an evaluated candidate into its corresponding island and prune low performers.

Source code in src/scale_forecasting/evolve/client.py
def add(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
    *,
    generation: int = 0,
) -> None:
    """Insert an evaluated candidate into its corresponding island and prune low performers."""
    if not math.isfinite(score):
        return
    island_id = int(generation) % self.n_islands
    cand = IslandCandidate(
        program_id=program_id,
        code=code,
        score=float(score),
        island_id=island_id,
        generation=int(generation),
        diagnostics=dict(diagnostics or {}),
    )
    bucket = self._islands[island_id]
    bucket.append(cand)
    bucket.sort(key=lambda c: c.score)
    if len(bucket) > self.max_per_island:
        del bucket[self.max_per_island :]

best

best()

Return the global best candidate across all islands.

Source code in src/scale_forecasting/evolve/client.py
def best(self) -> IslandCandidate | None:
    """Return the global best candidate across all islands."""
    all_cands = [c for b in self._islands.values() for c in b]
    return min(all_cands, key=lambda c: c.score) if all_cands else None

select_parent

select_parent(generation)

Select the lowest-loss parent from the active island for generation.

Source code in src/scale_forecasting/evolve/client.py
def select_parent(self, generation: int) -> IslandCandidate | None:
    """Select the lowest-loss parent from the active island for ``generation``."""
    island_id = int(generation) % self.n_islands
    bucket = self._islands.get(island_id, [])
    if bucket:
        return bucket[0]
    all_cands = [c for b in self._islands.values() for c in b]
    if not all_cands:
        return None
    return min(all_cands, key=lambda c: c.score)

MockEvolutionClient

MockEvolutionClient(
    target="features",
    candidates=None,
    max_evaluations=10,
    *,
    model_name=DEFAULT_GEMINI_MODEL,
)

Offline deterministic evolution transport for fast unit testing and CI --dry-run.

Source code in src/scale_forecasting/evolve/client.py
def __init__(
    self,
    target: str = "features",
    candidates: Sequence[str] | None = None,
    max_evaluations: int = 10,
    *,
    model_name: str = DEFAULT_GEMINI_MODEL,
) -> None:
    self.target = target
    self.model_name = model_name
    self._custom_candidates = list(candidates) if candidates is not None else None
    self.max_evaluations = max(1, int(max_evaluations))
    self.recorded_evaluations: list[dict[str, Any]] = []

propose_candidate

propose_candidate(
    target, parent_code, diagnostics=None, generation=1
)

Return deterministic candidate generation - 1 with zero network calls.

Source code in src/scale_forecasting/evolve/client.py
def propose_candidate(
    self,
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Return deterministic candidate ``generation - 1`` with zero network calls."""
    _ = (parent_code, diagnostics)
    spec = get_target_seed(target)
    if self._custom_candidates:
        raw = self._custom_candidates[(generation - 1) % len(self._custom_candidates)]
        if "def " in raw or "class " in raw:
            return raw
        return inject_evolve_block(spec.seed_code, raw)
    built_in = deterministic_mock_candidates(spec.target, count=max(3, self.max_evaluations))
    return built_in[(generation - 1) % len(built_in)]

record_evaluation

record_evaluation(
    program_id,
    code,
    score,
    diagnostics=None,
    *,
    generation=1,
)

Append evaluation telemetry to self.recorded_evaluations.

Source code in src/scale_forecasting/evolve/client.py
def record_evaluation(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
    *,
    generation: int = 1,
) -> None:
    """Append evaluation telemetry to ``self.recorded_evaluations``."""
    self.recorded_evaluations.append(
        {
            "program_id": program_id,
            "code": code,
            "score": float(score) if math.isfinite(score) else None,
            "generation": generation,
            "diagnostics": dict(diagnostics or {}),
        }
    )

VertexGeminiEvolutionClient

VertexGeminiEvolutionClient(
    project_id=None,
    region="us-central1",
    model_name=DEFAULT_GEMINI_MODEL,
    *,
    n_islands=3,
    temperature=0.4,
    genai_client=None,
)

Backup non-default evolution transport using standard Vertex AI Gemini.

Uses google.genai.Client(vertexai=True, project=project_id, location=region) (default model "gemini-3.8-flash", or any caller-supplied model_name) plus :class:IslandPopulationBuffer to mutate # EVOLVE-BLOCK code from walk-forward diagnostic feedback without requiring a Gemini Enterprise license.

Source code in src/scale_forecasting/evolve/client.py
def __init__(
    self,
    project_id: str | None = None,
    region: str = "us-central1",
    model_name: str = DEFAULT_GEMINI_MODEL,
    *,
    n_islands: int = 3,
    temperature: float = 0.4,
    genai_client: Any = None,
) -> None:
    self.project_id = (
        _resolve_project_id(project_id)
        if genai_client is None
        else (project_id or os.environ.get("SF_PROJECT_ID") or "mock-project")
    )
    self.region = region
    self.model_name = model_name
    self.temperature = temperature
    self.population = IslandPopulationBuffer(n_islands=n_islands)
    self._genai_client = genai_client
    self._custom_genai_client = genai_client is not None

propose_candidate

propose_candidate(
    target, parent_code, diagnostics=None, generation=1
)

Mutate # EVOLVE-BLOCK using Vertex AI Gemini + island population state.

Source code in src/scale_forecasting/evolve/client.py
def propose_candidate(
    self,
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Mutate ``# EVOLVE-BLOCK`` using Vertex AI Gemini + island population state."""
    spec = get_target_seed(target)
    island_parent = self.population.select_parent(generation)
    eff_parent = island_parent.code if island_parent is not None else parent_code
    eff_diag = (
        island_parent.diagnostics
        if (island_parent is not None and island_parent.diagnostics)
        else dict(diagnostics or {})
    )
    prompt = build_mutation_prompt(
        target=spec.target,
        parent_code=eff_parent,
        diagnostics=eff_diag,
        generation=generation,
    )
    raw_response = self._generate_text(spec.system_instruction, prompt)
    if not raw_response.strip():
        # Fallback to deterministic candidate if model response is empty
        cands = deterministic_mock_candidates(spec.target, count=max(1, generation))
        return cands[(generation - 1) % len(cands)]
    try:
        injected = inject_evolve_block(spec.seed_code, raw_response)
        if validate_candidate_ast(injected).valid:
            return injected
    except Exception as exc:  # noqa: BLE001 - malformed LLM block falls back cleanly
        _log.debug("Vertex Gemini candidate block failed AST validation: %s", exc)
    cands = deterministic_mock_candidates(spec.target, count=max(1, generation))
    return cands[(generation - 1) % len(cands)]

record_evaluation

record_evaluation(
    program_id,
    code,
    score,
    diagnostics=None,
    *,
    generation=1,
)

Record candidate score and walk-forward diagnostics into the island buffer.

Source code in src/scale_forecasting/evolve/client.py
def record_evaluation(
    self,
    program_id: str,
    code: str,
    score: float,
    diagnostics: Mapping[str, Any] | None = None,
    *,
    generation: int = 1,
) -> None:
    """Record candidate score and walk-forward diagnostics into the island buffer."""
    self.population.add(
        program_id=program_id,
        code=code,
        score=score,
        diagnostics=diagnostics,
        generation=generation,
    )

create_evolution_client

create_evolution_client(
    backend,
    *,
    target="features",
    project_id=None,
    location="global",
    region="us-central1",
    model_name=DEFAULT_GEMINI_MODEL,
    max_evaluations=10,
    mock_candidates=None,
    genai_client=None,
    alphaevolve_http_request=None,
)

Instantiate the requested evolution client backend.

Source code in src/scale_forecasting/evolve/client.py
def create_evolution_client(
    backend: str,
    *,
    target: str = "features",
    project_id: str | None = None,
    location: str = "global",
    region: str = "us-central1",
    model_name: str = DEFAULT_GEMINI_MODEL,
    max_evaluations: int = 10,
    mock_candidates: Sequence[str] | None = None,
    genai_client: Any = None,
    alphaevolve_http_request: Callable[..., dict[str, Any]] | None = None,
) -> AlphaEvolveClient | VertexGeminiEvolutionClient | MockEvolutionClient:
    """Instantiate the requested evolution client backend."""
    norm = str(backend).strip().lower()
    if norm == "alphaevolve":
        return AlphaEvolveClient(
            project_id=project_id,
            location=location,
            model_name=model_name,
            http_request=alphaevolve_http_request,
        )
    if norm == "vertex_gemini":
        return VertexGeminiEvolutionClient(
            project_id=project_id,
            region=region,
            model_name=model_name,
            genai_client=genai_client,
        )
    if norm == "mock":
        return MockEvolutionClient(
            target=target,
            candidates=mock_candidates,
            max_evaluations=max_evaluations,
            model_name=model_name,
        )
    raise ConfigurationError(
        f"Unknown evolution backend '{backend}'. Valid backends: "
        "'alphaevolve', 'vertex_gemini', 'mock'."
    )

probe_alphaevolve_access

probe_alphaevolve_access(
    project_id=None,
    location="global",
    *,
    timeout=10.0,
    http_get=None,
)

Fast pre-flight check verifying Discovery Engine AlphaEvolve entitlement before backtests.

Raises :class:~scale_forecasting.errors.ConfigError (aliased as ConfigurationError) if discoveryengine.googleapis.com is disabled or the project/organization lacks Gemini Enterprise AlphaEvolve entitlement (HTTP 403 / 404).

Source code in src/scale_forecasting/evolve/client.py
def probe_alphaevolve_access(
    project_id: str | None = None,
    location: str = "global",
    *,
    timeout: float = 10.0,
    http_get: Callable[..., Any] | None = None,
) -> dict[str, Any]:
    """Fast pre-flight check verifying Discovery Engine AlphaEvolve entitlement before backtests.

    Raises :class:`~scale_forecasting.errors.ConfigError` (aliased as ``ConfigurationError``) if
    ``discoveryengine.googleapis.com`` is disabled or the project/organization lacks Gemini
    Enterprise AlphaEvolve entitlement (``HTTP 403`` / ``404``).
    """
    resolved_project = _resolve_project_id(project_id)
    base_url = ALPHAEVOLVE_BASE_URL_TEMPLATE.format(
        project_id=resolved_project,
        location=location,
    )
    probe_url = f"{base_url}?pageSize=1"

    if http_get is not None:
        try:
            resp = http_get(probe_url, timeout=timeout)
        except urllib.error.HTTPError as exc:
            body_text = ""
            try:
                body_text = exc.read().decode("utf-8", errors="replace")
            except Exception:  # noqa: BLE001 - best-effort error body decode
                body_text = str(exc)
            raise ConfigurationError(
                _format_alphaevolve_entitlement_error(
                    resolved_project, location, exc.code, body_text
                )
            ) from exc
        except ConfigError:
            raise
        except Exception as exc:
            raise ConfigurationError(
                _format_alphaevolve_entitlement_error(resolved_project, location, "ERROR", str(exc))
            ) from exc

        if isinstance(resp, Mapping):
            status = int(resp.get("status", 200))
            if status in (401, 403, 404) or status >= 400:
                raise ConfigurationError(
                    _format_alphaevolve_entitlement_error(
                        resolved_project,
                        location,
                        status,
                        str(resp.get("error", resp.get("body", ""))),
                    )
                )
            return {
                "accessible": True,
                "backend": "alphaevolve",
                "project_id": resolved_project,
                "location": location,
                "endpoint": base_url,
                "response": dict(resp),
            }
        status_attr = getattr(resp, "status", getattr(resp, "status_code", 200))
        if int(status_attr) >= 400:
            raise ConfigurationError(
                _format_alphaevolve_entitlement_error(resolved_project, location, int(status_attr))
            )
        return {
            "accessible": True,
            "backend": "alphaevolve",
            "project_id": resolved_project,
            "location": location,
            "endpoint": base_url,
        }

    token = _get_adc_bearer_token(resolved_project)
    req = urllib.request.Request(
        probe_url,
        headers={
            "Authorization": f"Bearer {token}",
            "x-goog-user-project": resolved_project,
            "Content-Type": "application/json",
        },
        method="GET",
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as response:
            raw_body = response.read().decode("utf-8", errors="replace")
            parsed = json.loads(raw_body) if raw_body.strip().startswith("{") else {}
            return {
                "accessible": True,
                "backend": "alphaevolve",
                "project_id": resolved_project,
                "location": location,
                "endpoint": base_url,
                "response": parsed,
            }
    except urllib.error.HTTPError as exc:
        body_text = ""
        try:
            body_text = exc.read().decode("utf-8", errors="replace")
        except Exception:  # noqa: BLE001 - best-effort error body read
            body_text = str(exc)
        raise ConfigurationError(
            _format_alphaevolve_entitlement_error(resolved_project, location, exc.code, body_text)
        ) from exc
    except Exception as exc:
        raise ConfigurationError(
            _format_alphaevolve_entitlement_error(
                resolved_project, location, "UNREACHABLE", str(exc)
            )
        ) from exc

targets

Evolutionary targets (# EVOLVE-BLOCK) built on top of Forecaster.auto().

Defines the five bounded code-synthesis targets for scale_forecasting.evolve:

  1. "features" (:func:synthesize_evolved_features) — synthesizes causal lag, rolling, harmonic, and exogenous interaction covariates (evolved_feat_*) strictly from past and contemporaneous context without future target lookahead.
  2. "ensemble" (:func:compute_evolved_weights) — synthesizes custom out-of-fold (OOF) blending weights across the cached model bank produced by Forecaster.auto().
  3. "model" (:class:EvolvedForecaster) — synthesizes a custom :class:~scale_forecasting.models.base_model.BaseModel subclass using numpy/scipy/statsmodels primitives.
  4. "policy" (:func:evolve_policy_weights) — tunes :class:AutoPolicyWeights decision thresholds and action confidence priors for :mod:scale_forecasting.auto_policy.
  5. "similarity_kernel" (:func:compute_evolved_similarity_kernel) — synthesizes a custom positive-definite / pairwise time-series similarity kernel over multi-lens dynamical feature embeddings for analog transfer and cluster-aware cross-series pooling.

AutoPolicyWeights dataclass

AutoPolicyWeights(
    intermittent_share_min=0.165,
    log1p_level_vol_corr_min=0.635,
    log1p_growth_ratio_min=1.336,
    resid_hetero_min=0.3,
    structural_break_share_min=0.251,
    outlier_spike_share_min=0.195,
    direct_horizon_decay_ratio_min=1.323,
    resid_acf1_escalate_min=0.309,
    fva_escalate_min_pct=3.077,
    white_noise_growth_tol=0.179,
    white_noise_acf_season_max=0.17,
    require_white_noise_stop=True,
    pass_decay_factor=0.7,
    first_light_include_regression_lags=True,
    first_light_selection_rule="best_single",
    tree_n_estimators_fast=60,
    enable_similarity_global=True,
    similarity_silhouette_threshold=0.3,
    action_weights=_default_action_weights(),
)

Typed container of evolutionary thresholds for :mod:scale_forecasting.auto_policy.

from_defaults classmethod

from_defaults()

Construct :class:AutoPolicyWeights from auto_policy.evolved_policy_thresholds().

Source code in src/scale_forecasting/evolve/targets.py
@classmethod
def from_defaults(cls) -> AutoPolicyWeights:
    """Construct :class:`AutoPolicyWeights` from ``auto_policy.evolved_policy_thresholds()``."""
    return cls.from_dict(evolved_policy_thresholds())

from_dict classmethod

from_dict(data)

Construct :class:AutoPolicyWeights from a plain threshold dictionary.

Source code in src/scale_forecasting/evolve/targets.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> AutoPolicyWeights:
    """Construct :class:`AutoPolicyWeights` from a plain threshold dictionary."""
    valid_fields = set(cls.__dataclass_fields__)
    filtered: dict[str, Any] = {}
    for k, v in data.items():
        if k not in valid_fields:
            continue
        if k == "action_weights" and isinstance(v, Mapping):
            filtered[k] = {
                str(ak): (float(av[0]), float(av[1]))
                for ak, av in v.items()
                if isinstance(av, (tuple, list)) and len(av) == 2
            }
        else:
            filtered[k] = v
    return cls(**filtered)

to_dict

to_dict()

Serialize policy weights to a dictionary compatible with auto_policy.

Source code in src/scale_forecasting/evolve/targets.py
def to_dict(self) -> dict[str, Any]:
    """Serialize policy weights to a dictionary compatible with ``auto_policy``."""
    out = asdict(self)
    out["first_light_ensemble_strategies"] = ["inverse_error", "mean"]
    return out

with_updates

with_updates(**kwargs)

Return a copy of self with updated field values.

Source code in src/scale_forecasting/evolve/targets.py
def with_updates(self, **kwargs: Any) -> AutoPolicyWeights:
    """Return a copy of ``self`` with updated field values."""
    return replace(self, **kwargs)

EvolvedForecaster

EvolvedForecaster(params, ctx)

Bases: BaseModel

Custom evolutionary forecaster plugin (target='model').

Source code in src/scale_forecasting/evolve/targets.py
def __init__(self, params: dict[str, Any], ctx: ModelContext) -> None:
    super().__init__(params, ctx)
    self._last_ds: pd.Timestamp | None = None
    self._fitted_values: np.ndarray = np.array([], dtype=float)
    self._y_train: np.ndarray = np.array([], dtype=float)
    self._season_period: int = 7
    self._seasonal_profile: np.ndarray = np.zeros(7, dtype=float)
    self._level: float = 0.0
    self._slope: float = 0.0
    self._exog_cols: list[str] = []
    self._exog_coef: np.ndarray = np.array([], dtype=float)
    self._exog_mean: np.ndarray = np.array([], dtype=float)

fit

fit(y, X=None)

Fit evolutionary damped trend + harmonic seasonal + ridge exogenous model.

Source code in src/scale_forecasting/evolve/targets.py
def fit(self, y: pd.Series, X: pd.DataFrame | None = None) -> None:
    """Fit evolutionary damped trend + harmonic seasonal + ridge exogenous model."""
    y_vals = pd.to_numeric(y, errors="coerce").ffill().bfill().fillna(0.0).to_numpy(dtype=float)
    self._y_train = y_vals
    if isinstance(y.index, pd.DatetimeIndex) and len(y.index) > 0:
        self._last_ds = pd.Timestamp(y.index[-1])
    elif X is not None and "ds" in X.columns and len(X) > 0:
        self._last_ds = pd.Timestamp(X["ds"].iloc[-1])
    else:
        self._last_ds = pd.Timestamp("2025-01-01")
    self._last_date = self._last_ds

    n = len(y_vals)
    if n == 0:
        self._fitted_values = np.zeros(1, dtype=float)
        self._set_residuals(np.zeros(1, dtype=float))
        return

    # EVOLVE-BLOCK-START
    freq_str = str(self.ctx.freq).upper()
    if freq_str.startswith("M"):
        period = 12
    elif freq_str.startswith("W"):
        period = 13
    elif freq_str.startswith("Q"):
        period = 4
    elif freq_str.startswith("H"):
        period = 24
    else:
        period = 7
    self._season_period = max(1, min(period, max(1, n // 2)))

    t = np.arange(n, dtype=float)
    if n >= 4:
        t_mean = float(np.mean(t))
        y_mean = float(np.mean(y_vals))
        denom = float(np.dot(t - t_mean, t - t_mean)) + 1e-6
        raw_slope = float(np.dot(t - t_mean, y_vals - y_mean)) / denom
        self._slope = 0.85 * raw_slope
        trend_line = y_mean + raw_slope * (t - t_mean)
        self._level = float(trend_line[-1])
    else:
        self._slope = 0.0
        self._level = float(np.mean(y_vals))
        trend_line = np.full(n, self._level, dtype=float)

    detrended = y_vals - trend_line
    s_prof = np.zeros(self._season_period, dtype=float)
    for rem in range(self._season_period):
        vals_rem = detrended[rem :: self._season_period]
        if len(vals_rem) > 0:
            s_prof[rem] = float(np.median(vals_rem))
    s_prof -= float(np.mean(s_prof))
    self._seasonal_profile = s_prof

    seasonal_comp = np.array(
        [s_prof[i % self._season_period] for i in range(n)],
        dtype=float,
    )
    resid = detrended - seasonal_comp
    self._exog_cols = []
    self._exog_coef = np.array([], dtype=float)
    self._exog_mean = np.array([], dtype=float)
    exog_fit = np.zeros(n, dtype=float)
    if X is not None and not X.empty:
        num_cols = [
            c
            for c in X.columns
            if c not in ("ds", "ts_id", "y") and pd.api.types.is_numeric_dtype(X[c])
        ]
        if num_cols:
            self._exog_cols = num_cols
            x_mat = (
                X[num_cols]
                .apply(pd.to_numeric, errors="coerce")
                .fillna(0.0)
                .to_numpy(dtype=float)
            )
            self._exog_mean = np.mean(x_mat, axis=0)
            x_c = x_mat - self._exog_mean
            gram = x_c.T @ x_c + 1.0 * np.eye(len(num_cols))
            self._exog_coef = np.linalg.solve(gram, x_c.T @ resid)
            exog_fit = x_c @ self._exog_coef

    self._fitted_values = trend_line + seasonal_comp + exog_fit
    # EVOLVE-BLOCK-END
    self._set_residuals(self._y_train - self._fitted_values)

predict

predict(horizon, X=None, quantiles=DEFAULT_QUANTILES)

Predict horizon steps ahead with calibrated residual intervals.

Source code in src/scale_forecasting/evolve/targets.py
def predict(
    self,
    horizon: int,
    X: pd.DataFrame | None = None,
    quantiles: tuple[float, ...] = DEFAULT_QUANTILES,
) -> pd.DataFrame:
    """Predict ``horizon`` steps ahead with calibrated residual intervals."""
    h = int(horizon)
    n = len(self._y_train)
    if X is not None and "ds" in X.columns and len(X) >= h:
        ds = pd.DatetimeIndex(pd.to_datetime(X["ds"].iloc[:h]))
    else:
        start = self._last_ds if self._last_ds is not None else pd.Timestamp("2025-01-01")
        freq = self.ctx.freq or "D"
        ds = pd.date_range(start=start, periods=h + 1, freq=freq)[1:]

    # EVOLVE-BLOCK-START
    steps = np.arange(1, h + 1, dtype=float)
    damping = (1.0 - np.power(0.90, steps)) / (1.0 - 0.90)
    base_level = (
        float(self._fitted_values[-1] - self._seasonal_profile[(n - 1) % self._season_period])
        if n > 0 and len(self._seasonal_profile) > 0
        else self._level
    )
    seasonal_fut = np.array(
        [
            self._seasonal_profile[(n + step - 1) % self._season_period]
            for step in range(1, h + 1)
        ],
        dtype=float,
    )
    yhat_raw = base_level + self._slope * damping + seasonal_fut

    if self._exog_cols and X is not None and not X.empty:
        present = [c for c in self._exog_cols if c in X.columns]
        if len(present) == len(self._exog_cols):
            x_fut = (
                X[self._exog_cols]
                .iloc[:h]
                .apply(pd.to_numeric, errors="coerce")
                .fillna(0.0)
                .to_numpy(dtype=float)
            )
            if len(x_fut) == h:
                yhat_raw = yhat_raw + (x_fut - self._exog_mean) @ self._exog_coef
    # EVOLVE-BLOCK-END

    qmap = self.residual_intervals(yhat_raw, quantiles=tuple(quantiles))
    return self._assemble_frame(ds, qmap, raw=yhat_raw)

TargetSpec dataclass

TargetSpec(
    target,
    entrypoint,
    description,
    seed_code,
    system_instruction,
    mutation_prompt_template,
)

Specification and seed program for one # EVOLVE-BLOCK evolutionary target.

build_mutation_prompt

build_mutation_prompt(
    target, parent_code, diagnostics=None, generation=1
)

Render a diagnostic-guided mutation prompt for target.

Source code in src/scale_forecasting/evolve/targets.py
def build_mutation_prompt(
    target: str,
    parent_code: str,
    diagnostics: Mapping[str, Any] | None = None,
    generation: int = 1,
) -> str:
    """Render a diagnostic-guided mutation prompt for ``target``."""
    spec = get_target_seed(target)
    diag_dict = dict(diagnostics or {})
    diag_summary = (
        f"fva_pct={diag_dict.get('fva_pct', 0.0):.2f}%, "
        f"dm_pvalue={diag_dict.get('dm_pvalue', 1.0):.4f}, "
        f"worst_decile_fva={diag_dict.get('worst_decile_fva', 0.0):.4f}, "
        f"horizon_decay={diag_dict.get('horizon_decay', 'stable')}, "
        f"inner_cv_score={diag_dict.get('inner_cv_score', 'n/a')}, "
        f"baseline_score={diag_dict.get('baseline_score', 'n/a')}, "
        f"monotonic_constraints={diag_dict.get('monotonic_constraints', {})}, "
        f"is_compositional_simplex={diag_dict.get('is_compositional_simplex', False)}, "
        f"simplex_total={diag_dict.get('simplex_total')}, "
        f"hierarchy_id_cols={diag_dict.get('hierarchy_id_cols', [])}, "
        f"reconcile_temporal={diag_dict.get('reconcile_temporal', False)}, "
        f"has_cold_start={diag_dict.get('has_cold_start', False)}, "
        f"cold_start_fraction={diag_dict.get('cold_start_fraction', 0.0)}, "
        f"cold_start_donor_similarity={diag_dict.get('cold_start_donor_similarity', 0.0)}, "
        f"calibration_method={diag_dict.get('calibration_method', 'conformal')}, "
        f"residual_drift_ks_stat={diag_dict.get('residual_drift_ks_stat', 0.0)}, "
        f"cross_series_residual_corr={diag_dict.get('cross_series_residual_corr', 0.0)}"
    )
    return spec.mutation_prompt_template.format(
        generation=generation,
        diagnostics=diag_summary,
        parent_code=parent_code.strip(),
    )

compute_evolved_similarity_kernel

compute_evolved_similarity_kernel(
    features_mat, profile=None
)

Synthesize an (N, N) similarity matrix in [0.0, 1.0] over per-series embeddings.

Source code in src/scale_forecasting/evolve/targets.py
def compute_evolved_similarity_kernel(
    features_mat: np.ndarray,
    profile: dict[str, Any] | None = None,
) -> np.ndarray:
    """Synthesize an ``(N, N)`` similarity matrix in ``[0.0, 1.0]`` over per-series embeddings."""
    _ = profile
    x_raw = np.asarray(features_mat, dtype=float)
    if x_raw.ndim == 1:
        x_raw = x_raw.reshape(-1, 1)
    n_series = int(x_raw.shape[0])
    if n_series <= 1:
        return np.ones((max(1, n_series), max(1, n_series)), dtype=float)
    x_clean = np.nan_to_num(x_raw, nan=0.0, posinf=0.0, neginf=0.0)
    col_mean = np.mean(x_clean, axis=0, keepdims=True)
    col_std = np.where(
        np.std(x_clean, axis=0, keepdims=True) > 1e-8, np.std(x_clean, axis=0, keepdims=True), 1.0
    )
    x_norm = (x_clean - col_mean) / col_std

    # EVOLVE-BLOCK-START
    norms = np.linalg.norm(x_norm, axis=1, keepdims=True)
    norms = np.where(norms > 1e-8, norms, 1.0)
    unit_x = x_norm / norms
    cos_sim = np.clip(unit_x @ unit_x.T, -1.0, 1.0)
    sq_dists = np.sum((x_norm[:, None, :] - x_norm[None, :, :]) ** 2, axis=-1)
    med_sq = float(np.median(sq_dists)) if sq_dists.size > 0 else 1.0
    rbf_sim = np.exp(-sq_dists / max(1e-6, 2.0 * med_sq))
    sim_matrix = 0.55 * np.maximum(0.0, cos_sim) + 0.45 * rbf_sim
    # EVOLVE-BLOCK-END

    sim_out = np.asarray(sim_matrix, dtype=float)
    sim_out = np.nan_to_num(sim_out, nan=0.0, posinf=1.0, neginf=0.0)
    sim_out = 0.5 * (sim_out + sim_out.T)
    sim_out = np.clip(sim_out, 0.0, 1.0)
    np.fill_diagonal(sim_out, 1.0)
    return sim_out

compute_evolved_weights

compute_evolved_weights(oof_df, profile=None)

Compute global (dict[str, float]) or per-series (dict[str, dict[str, float]]) weights.

Source code in src/scale_forecasting/evolve/targets.py
def compute_evolved_weights(
    oof_df: pd.DataFrame,
    profile: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Compute global (`dict[str, float]`) or per-series (`dict[str, dict[str, float]]`) weights."""
    _ = profile
    if oof_df.empty or "model_type" not in oof_df.columns:
        return {}
    work = oof_df.copy()
    date_col = (
        "ds"
        if "ds" in work.columns
        else ("forecast_date" if "forecast_date" in work.columns else "")
    )
    per_series_weights: dict[str, dict[str, float]] = {}

    # EVOLVE-BLOCK-START
    scores: dict[str, float] = {}
    for model_type, grp in work.groupby("model_type", sort=False):
        y_true = pd.to_numeric(grp["y_true"], errors="coerce").to_numpy(dtype=float)
        yhat = pd.to_numeric(grp["yhat"], errors="coerce").to_numpy(dtype=float)
        mask = np.isfinite(y_true) & np.isfinite(yhat)
        if not mask.any():
            continue
        abs_err = np.abs(y_true[mask] - yhat[mask])
        denom = max(1e-6, float(np.sum(np.abs(y_true[mask]))))
        wape = float(np.sum(abs_err)) / denom
        scores[str(model_type)] = 1.0 / max(1e-6, wape**2)
    # EVOLVE-BLOCK-END

    if per_series_weights:
        return per_series_weights

    total = sum(v for v in scores.values() if math.isfinite(v) and v > 0.0)
    if total <= 0.0:
        models = sorted(work["model_type"].astype(str).unique())
        global_w = {m: 1.0 / len(models) for m in models} if models else {}
    else:
        global_w = {k: float(v) / total for k, v in scores.items() if math.isfinite(v) and v > 0.0}

    if "ts_id" not in work.columns or not date_col or work["ts_id"].nunique() < 2 or not global_w:
        return global_w

    # Fold-consistent per-series adaptive shrinkage around the global champion
    model_mean_wape: dict[str, float] = {}
    for m_name, grp_m in work.groupby("model_type", sort=False):
        s_losses: list[float] = []
        for _, grp_s in grp_m.groupby("ts_id", sort=False):
            yt_s = pd.to_numeric(grp_s["y_true"], errors="coerce").to_numpy(dtype=float)
            yh_s = pd.to_numeric(grp_s["yhat"], errors="coerce").to_numpy(dtype=float)
            mk = np.isfinite(yt_s) & np.isfinite(yh_s)
            if mk.any():
                s_losses.append(
                    float(np.sum(np.abs(yt_s[mk] - yh_s[mk])))
                    / max(1e-6, float(np.sum(np.abs(yt_s[mk]))))
                )
        if s_losses:
            model_mean_wape[str(m_name)] = float(np.mean(s_losses))
    champ_m = (
        min(model_mean_wape, key=lambda k: model_mean_wape[k])
        if model_mean_wape
        else max(global_w, key=lambda k: global_w[k])
    )

    adaptive_map: dict[str, dict[str, float]] = {}
    for tid, grp_t in work.groupby("ts_id", sort=True):
        piv = grp_t.pivot_table(
            index=date_col, columns="model_type", values="yhat", aggfunc="first"
        ).sort_index()
        yt = pd.to_numeric(
            grp_t.groupby(date_col)["y_true"].first().reindex(piv.index), errors="coerce"
        ).to_numpy(dtype=float)
        if champ_m not in piv.columns or len(yt) < 2:
            adaptive_map[str(tid)] = dict(global_w)
            continue
        yc = pd.to_numeric(piv[champ_m], errors="coerce").to_numpy(dtype=float)
        base_err = np.abs(yt - yc)
        mid = max(1, len(yt) // 2)
        best_w: dict[str, float] = {champ_m: 1.0}
        best_loss = float(np.sum(base_err))

        # Test global_w blend on this series
        yg = np.zeros_like(yt)
        wg_sum = 0.0
        for m_k, w_k in global_w.items():
            if m_k in piv.columns:
                ym_k = pd.to_numeric(piv[m_k], errors="coerce").to_numpy(dtype=float)
                if np.isfinite(ym_k).all():
                    yg = yg + w_k * ym_k
                    wg_sum += w_k
        if wg_sum > 1e-9:
            yg = yg / wg_sum
            err_g = np.abs(yt - yg)
            if (
                float(np.sum(err_g)) < best_loss - 1e-6
                and float(np.sum(err_g[:mid])) <= float(np.sum(base_err[:mid]))
                and float(np.sum(err_g[mid:])) <= float(np.sum(base_err[mid:]))
                and float(np.mean(err_g <= base_err)) >= 0.55
            ):
                best_loss = float(np.sum(err_g))
                best_w = {m_k: w_k / wg_sum for m_k, w_k in global_w.items() if m_k in piv.columns}

        # Test fold-consistent pairwise blends with global champion
        for m_col in piv.columns:
            m_str = str(m_col)
            if m_str == champ_m:
                continue
            ym = pd.to_numeric(piv[m_col], errors="coerce").to_numpy(dtype=float)
            if not np.isfinite(ym).all():
                continue
            for alpha in (-0.08, 0.15, 0.25, 0.35, 0.50, 0.65, 0.80):
                y_blend = (1.0 - alpha) * yc + alpha * ym
                err_b = np.abs(yt - y_blend)
                if (
                    float(np.sum(err_b)) < best_loss - 1e-6
                    and float(np.sum(err_b[:mid])) <= float(np.sum(base_err[:mid]))
                    and float(np.sum(err_b[mid:])) <= float(np.sum(base_err[mid:]))
                    and float(np.mean(err_b <= base_err)) >= 0.55
                ):
                    best_loss = float(np.sum(err_b))
                    best_w = {champ_m: round(1.0 - alpha, 4), m_str: round(alpha, 4)}
        adaptive_map[str(tid)] = best_w
    return adaptive_map

deterministic_mock_candidates

deterministic_mock_candidates(target, count=3)

Return count deterministic, AST-safe, causal candidate programs for target.

Source code in src/scale_forecasting/evolve/targets.py
def deterministic_mock_candidates(target: str, count: int = 3) -> list[str]:
    """Return ``count`` deterministic, AST-safe, causal candidate programs for ``target``."""
    spec = get_target_seed(target)
    blocks_by_target: dict[str, tuple[str, ...]] = {
        "features": _MOCK_FEATURES_BLOCKS,
        "ensemble": _MOCK_ENSEMBLE_BLOCKS,
        "model": _MOCK_MODEL_BLOCKS,
        "policy": _MOCK_POLICY_BLOCKS,
        "similarity_kernel": _MOCK_SIMILARITY_KERNEL_BLOCKS,
    }
    blocks = blocks_by_target[spec.target]
    candidates: list[str] = []
    for idx in range(max(1, count)):
        blk = blocks[idx % len(blocks)]
        candidates.append(inject_evolve_block(spec.seed_code, blk))
    return candidates

evolve_policy_weights

evolve_policy_weights(base_weights)

Tune :class:AutoPolicyWeights thresholds for auto_policy (target='policy').

Source code in src/scale_forecasting/evolve/targets.py
def evolve_policy_weights(base_weights: AutoPolicyWeights) -> AutoPolicyWeights:
    """Tune :class:`AutoPolicyWeights` thresholds for ``auto_policy`` (`target='policy'`)."""
    # EVOLVE-BLOCK-START
    updated_actions = dict(base_weights.action_weights)
    updated_actions["prune_decoy_covariates"] = (0.90, 7.5)
    updated_actions["inject_transform_log1p"] = (0.93, 10.8)
    updated_actions["inject_direct_horizon_models"] = (0.86, 6.2)
    updated_actions["inject_monotone_guardrails"] = (0.88, 7.0)
    updated_actions["inject_transform_simplex"] = (0.89, 8.4)
    updated_actions["enable_temporal_reconciliation"] = (0.81, 5.2)
    updated_actions["enable_cold_start_transfer"] = (0.86, 6.8)
    updated_actions["enable_adaptive_conformal"] = (0.83, 5.4)
    return base_weights.with_updates(
        intermittent_share_min=0.16,
        log1p_level_vol_corr_min=0.60,
        log1p_growth_ratio_min=1.30,
        direct_horizon_decay_ratio_min=1.28,
        pass_decay_factor=0.74,
        action_weights=updated_actions,
    )

extract_evolve_block

extract_evolve_block(code)

Extract the code lines between # EVOLVE-BLOCK-START and # EVOLVE-BLOCK-END.

If the markers are absent from code, returns normalized dedented code.

Source code in src/scale_forecasting/evolve/targets.py
def extract_evolve_block(code: str) -> str:
    """Extract the code lines between ``# EVOLVE-BLOCK-START`` and ``# EVOLVE-BLOCK-END``.

    If the markers are absent from ``code``, returns normalized dedented ``code``.
    """
    text = str(code)
    start_idx = text.find(EVOLVE_BLOCK_START)
    end_idx = text.find(EVOLVE_BLOCK_END)
    if start_idx == -1 or end_idx == -1 or end_idx < start_idx:
        return _normalize_block_indent(text)
    inner = text[start_idx + len(EVOLVE_BLOCK_START) : end_idx]
    return _normalize_block_indent(inner)

get_target_seed

get_target_seed(target)

Return the canonical :class:TargetSpec for target.

Source code in src/scale_forecasting/evolve/targets.py
def get_target_seed(target: str) -> TargetSpec:
    """Return the canonical :class:`TargetSpec` for ``target``."""
    norm = str(target).strip().lower()
    if norm not in _TARGET_SPECS:
        valid = ", ".join(EVOLVE_TARGETS)
        raise ConfigError(f"Unknown evolve target '{target}'. Valid targets: {valid}")
    return _TARGET_SPECS[norm]

inject_evolve_block

inject_evolve_block(template, block)

Inject block between # EVOLVE-BLOCK-START and # EVOLVE-BLOCK-END in template.

Handles both: - an inner snippet (indented to match # EVOLVE-BLOCK-START in template), and - a full program that already contains # EVOLVE-BLOCK-START / # EVOLVE-BLOCK-END (its inner block is extracted first and injected into template).

Source code in src/scale_forecasting/evolve/targets.py
def inject_evolve_block(template: str, block: str) -> str:
    """Inject ``block`` between ``# EVOLVE-BLOCK-START`` and ``# EVOLVE-BLOCK-END`` in ``template``.

    Handles both:
    - an inner snippet (indented to match ``# EVOLVE-BLOCK-START`` in ``template``), and
    - a full program that already contains ``# EVOLVE-BLOCK-START`` / ``# EVOLVE-BLOCK-END`` (its
      inner block is extracted first and injected into ``template``).
    """
    clean_block = str(block).strip("\r\n")
    fence_match = re.search(r"```(?:python)?[ \t]*\r?\n(.*?)```", clean_block, flags=re.DOTALL)
    if fence_match:
        clean_block = fence_match.group(1).strip("\r\n")

    if EVOLVE_BLOCK_START in clean_block and EVOLVE_BLOCK_END in clean_block:
        clean_block = extract_evolve_block(clean_block)

    if EVOLVE_BLOCK_START not in template or EVOLVE_BLOCK_END not in template:
        raise ConfigError(f"Template is missing {EVOLVE_BLOCK_START} / {EVOLVE_BLOCK_END} markers.")

    lines = template.splitlines()
    out_lines: list[str] = []
    in_block = False
    injected = False
    for line in lines:
        if EVOLVE_BLOCK_START in line and not injected:
            indent = line[: len(line) - len(line.lstrip())]
            out_lines.append(line)
            dedented = _normalize_block_indent(clean_block)
            for b_line in dedented.splitlines():
                out_lines.append(f"{indent}{b_line}" if b_line.strip() else "")
            in_block = True
            injected = True
            continue
        if EVOLVE_BLOCK_END in line and in_block:
            in_block = False
            out_lines.append(line)
            continue
        if not in_block:
            out_lines.append(line)

    return "\n".join(out_lines) + "\n"

synthesize_evolved_features

synthesize_evolved_features(df, profile=None)

Synthesize causal evolved_feat_* columns without future target lookahead.

Source code in src/scale_forecasting/evolve/targets.py
def synthesize_evolved_features(
    df: pd.DataFrame,
    profile: dict[str, Any] | None = None,
) -> pd.DataFrame:
    """Synthesize causal ``evolved_feat_*`` columns without future target lookahead."""
    out = df.copy()
    id_col = str((profile or {}).get("ts_id_col", "ts_id"))
    if id_col not in out.columns:
        id_col = "ts_id" if "ts_id" in out.columns else out.columns[0]

    # EVOLVE-BLOCK-START
    step_idx = out.groupby(id_col, sort=False).cumcount().to_numpy(dtype=float)
    out["evolved_feat_trend_idx"] = np.log1p(step_idx)
    out["evolved_feat_sin_w"] = np.sin(2.0 * np.pi * step_idx / 7.0)
    out["evolved_feat_cos_w"] = np.cos(2.0 * np.pi * step_idx / 7.0)

    reserved = {id_col, "ts_id", "ds", "date", "forecast_date", "y", "y_true", "yhat"}
    exog_cols = [
        c
        for c in out.columns
        if c not in reserved
        and not str(c).startswith("evolved_feat_")
        and pd.api.types.is_numeric_dtype(out[c])
    ]
    for col in exog_cols[:3]:
        vals = pd.to_numeric(out[col], errors="coerce").fillna(0.0)
        out[f"evolved_feat_{col}_lag1"] = (
            vals.groupby(out[id_col], sort=False).shift(1).fillna(vals)
        )
        out[f"evolved_feat_{col}_roll3"] = (
            vals.groupby(out[id_col], sort=False)
            .transform(lambda s: s.rolling(3, min_periods=1).mean())
            .astype(float)
        )
    # EVOLVE-BLOCK-END
    return out

sandbox

AST security sandbox, wall-clock timeout executor, and temporal lookahead leak detector.

Enforces three non-negotiable pre-gate invariants on every candidate program before any cross- validation fold is scored:

  1. AST Security Sandbox (:func:validate_candidate_ast): Rejects prohibited system/network/file imports (os, sys, subprocess, socket, urllib, http, pathlib, shutil, ctypes, pickle, builtins, importlib) and dangerous builtins or reflection calls (eval, exec, open, compile, __import__, getattr, setattr, globals, locals). Only whitelisted scientific modules (numpy, pandas, scipy, statsmodels, sklearn, math, statistics, scale_forecasting) may be imported.
  2. Temporal Causality & Future-Leakage Detector (:func:verify_no_future_leakage): Perturbs the last horizon target rows per series with +1e6 sentinel noise and verifies that all engineered features or predictions at earlier timestamps $t \le T - H$ remain bit-for-bit identical (np.allclose(..., atol=1e-12)).
  3. Bounded Sandbox Execution (:func:execute_in_sandbox): Compiles AST-verified code inside a restricted builtins namespace under a strict wall-clock timeout.

SandboxValidationResult dataclass

SandboxValidationResult(
    valid, violations=(), ast_node_count=0
)

Result of static AST security inspection on a candidate program.

errors property

errors

Alias for self.violations.

is_valid property

is_valid

Alias for self.valid.

reason property

reason

Joined violation summary string, or None when valid.

compile_candidate_symbol

compile_candidate_symbol(code, entrypoint)

Validate code with :func:validate_candidate_ast and return entrypoint.

Source code in src/scale_forecasting/evolve/sandbox.py
def compile_candidate_symbol(code: str, entrypoint: str) -> Any:
    """Validate ``code`` with :func:`validate_candidate_ast` and return ``entrypoint``."""
    validation = validate_candidate_ast(code)
    if not validation.valid:
        raise ConfigError(f"Candidate failed AST security sandbox: {validation.reason}")

    env: dict[str, Any] = {
        "__builtins__": dict(_SAFE_BUILTINS),
        "np": np,
        "numpy": np,
        "pd": pd,
        "pandas": pd,
        "math": math,
        "statistics": statistics,
        "scipy": scipy,
        "stats": scipy_stats,
        "BaseModel": BaseModel,
        "ModelContext": ModelContext,
        "DEFAULT_QUANTILES": DEFAULT_QUANTILES,
        "AutoPolicyWeights": AutoPolicyWeights,
    }
    compiled = compile(code, filename="<evolve_candidate>", mode="exec")
    exec(compiled, env)
    if entrypoint not in env:
        raise ConfigError(f"Candidate code did not define required entrypoint '{entrypoint}'.")
    return env[entrypoint]

execute_in_sandbox

execute_in_sandbox(
    code, entrypoint, *args, timeout_seconds=10.0, **kwargs
)

Compile and execute entrypoint(*args, **kwargs) with a hard wall-clock timeout.

Source code in src/scale_forecasting/evolve/sandbox.py
def execute_in_sandbox(
    code: str,
    entrypoint: str,
    *args: Any,
    timeout_seconds: float = 10.0,
    **kwargs: Any,
) -> Any:
    """Compile and execute ``entrypoint(*args, **kwargs)`` with a hard wall-clock timeout."""
    symbol = compile_candidate_symbol(code, entrypoint)
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
        future = pool.submit(symbol, *args, **kwargs)
        try:
            return future.result(timeout=max(0.5, float(timeout_seconds)))
        except concurrent.futures.TimeoutError as exc:
            raise TimeoutError(
                f"Candidate '{entrypoint}' exceeded sandbox timeout ({timeout_seconds:.1f}s)."
            ) from exc

validate_candidate_ast

validate_candidate_ast(code)

Parse code into an AST and reject prohibited imports, calls, and reflection.

Source code in src/scale_forecasting/evolve/sandbox.py
def validate_candidate_ast(code: str) -> SandboxValidationResult:
    """Parse ``code`` into an AST and reject prohibited imports, calls, and reflection."""
    if not isinstance(code, str) or not code.strip():
        return SandboxValidationResult(
            valid=False,
            violations=("Candidate code is empty.",),
            ast_node_count=0,
        )

    try:
        tree = ast.parse(code)
    except SyntaxError as exc:
        return SandboxValidationResult(
            valid=False,
            violations=(f"SyntaxError at line {exc.lineno}: {exc.msg}",),
            ast_node_count=0,
        )

    violations: list[str] = []
    node_count = 0

    for node in ast.walk(tree):
        node_count += 1
        if node_count > _MAX_AST_NODES:
            violations.append(f"AST node count exceeds maximum limit ({_MAX_AST_NODES}).")
            break

        if isinstance(node, ast.Import):
            for alias in node.names:
                root_mod = alias.name.split(".", 1)[0]
                if root_mod in PROHIBITED_MODULES:
                    violations.append(f"Prohibited import '{alias.name}'.")
                elif root_mod not in ALLOWED_MODULES:
                    violations.append(
                        f"Import '{alias.name}' is not in the allowed scientific module whitelist."
                    )

        elif isinstance(node, ast.ImportFrom):
            mod_name = node.module or ""
            root_mod = mod_name.split(".", 1)[0] if mod_name else ""
            if root_mod in PROHIBITED_MODULES:
                violations.append(f"Prohibited import from '{mod_name}'.")
            elif root_mod and root_mod not in ALLOWED_MODULES:
                violations.append(
                    f"Import from '{mod_name}' is not in the allowed scientific module whitelist."
                )
            for alias in node.names:
                if alias.name in PROHIBITED_MODULES or alias.name in PROHIBITED_CALLS:
                    violations.append(f"Prohibited symbol import '{alias.name}'.")

        elif isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                fn_name = node.func.id
                if fn_name in PROHIBITED_CALLS:
                    violations.append(f"Prohibited function call '{fn_name}()'.")
            elif isinstance(node.func, ast.Attribute):
                attr_name = node.func.attr
                if attr_name in PROHIBITED_CALLS:
                    violations.append(f"Prohibited method call '.{attr_name}()'.")
                if attr_name in (
                    "to_csv",
                    "to_parquet",
                    "to_pickle",
                    "read_csv",
                    "read_pickle",
                    "read_parquet",
                ):
                    violations.append(f"Prohibited file I/O method call '.{attr_name}()'.")

        elif isinstance(node, ast.Attribute):
            if node.attr in _PROHIBITED_DUNDER_ATTRS:
                violations.append(f"Prohibited dunder attribute access '.{node.attr}'.")

        elif isinstance(node, ast.Name) and node.id in ("__builtins__", "__import__"):
            violations.append(f"Prohibited identifier '{node.id}'.")

    return SandboxValidationResult(
        valid=(len(violations) == 0),
        violations=tuple(dict.fromkeys(violations)),
        ast_node_count=node_count,
    )

verify_no_future_leakage

verify_no_future_leakage(
    fn,
    df,
    target_col="y",
    time_col="ds",
    id_col="ts_id",
    horizon=7,
)

Verify that perturbing the last horizon target values by +1e6 does not alter any engineered features or fitted values on earlier timestamps $t \le T - H$.

Returns True only when all outputs on $t \le T - H$ are bit-for-bit identical (np.allclose(..., atol=1e-12, equal_nan=True)). Immediately returns False if the candidate uses future information (such as .shift(-k), .bfill(), or full-series global target aggregations).

Source code in src/scale_forecasting/evolve/sandbox.py
def verify_no_future_leakage(
    fn: Any,
    df: pd.DataFrame,
    target_col: str = "y",
    time_col: str = "ds",
    id_col: str = "ts_id",
    horizon: int = 7,
) -> bool:
    """Verify that perturbing the last ``horizon`` target values by ``+1e6`` does not alter
    any engineered features or fitted values on earlier timestamps $t \\le T - H$.

    Returns ``True`` only when all outputs on $t \\le T - H$ are bit-for-bit identical
    (``np.allclose(..., atol=1e-12, equal_nan=True)``). Immediately returns ``False`` if the
    candidate uses future information (such as ``.shift(-k)``, ``.bfill()``, or full-series
    global target aggregations).
    """
    if df.empty or target_col not in df.columns:
        return False

    h = max(1, int(horizon))
    work = df.copy()
    if id_col not in work.columns:
        work[id_col] = "series_0"
    if time_col in work.columns:
        work = work.sort_values([id_col, time_col]).reset_index(drop=True)
    else:
        work = work.reset_index(drop=True)

    # Handle BaseModel subclass (target="model")
    if isinstance(fn, type) and issubclass(fn, BaseModel):
        try:
            first_id = str(work[id_col].iloc[0])
            s_df = work[work[id_col].astype(str) == first_id].reset_index(drop=True)
            if len(s_df) <= h + 2:
                return True
            y_clean = pd.Series(
                pd.to_numeric(s_df[target_col], errors="coerce").to_numpy(dtype=float),
                index=pd.to_datetime(s_df[time_col]) if time_col in s_df.columns else None,
            )
            y_pert = y_clean.copy()
            y_pert.iloc[-h:] = y_pert.iloc[-h:] + 1e6

            ctx = ModelContext(freq="D", horizon=h)
            m_clean = fn({}, ctx)
            m_clean.fit(y_clean.iloc[:-h])
            m_pert = fn({}, ctx)
            m_pert.fit(y_pert.iloc[:-h])
            p_clean = m_clean.predict(h)["yhat"].to_numpy(dtype=float)
            p_pert = m_pert.predict(h)["yhat"].to_numpy(dtype=float)
            return bool(np.allclose(p_clean, p_pert, atol=1e-12, rtol=1e-9, equal_nan=True))
        except Exception:  # noqa: BLE001 - any failure inside candidate model rejects it
            return False

    # Build prefix mask (True for earlier timestamps t <= T - H, False for last H rows per series)
    prefix_mask = np.ones(len(work), dtype=bool)
    df_clean = work.copy()
    df_perturbed = work.copy()
    df_perturbed[target_col] = pd.to_numeric(df_perturbed[target_col], errors="coerce").astype(
        float
    )

    for _, grp in work.groupby(id_col, sort=False):
        idx = grp.index.to_numpy()
        eff_h = min(h, max(1, len(idx) // 2))
        tail_idx = idx[-eff_h:]
        prefix_mask[tail_idx] = False
        df_perturbed.loc[tail_idx, target_col] = (
            df_perturbed.loc[tail_idx, target_col].to_numpy(dtype=float) + 1e6
        )

    try:
        out_clean = fn(df_clean)
        out_perturbed = fn(df_perturbed)
    except TypeError:
        try:
            out_clean = fn(df_clean, None)
            out_perturbed = fn(df_perturbed, None)
        except Exception:  # noqa: BLE001 - candidate raised during causality check
            return False
    except Exception:  # noqa: BLE001 - candidate raised during causality check
        return False

    if not isinstance(out_clean, pd.DataFrame) or not isinstance(out_perturbed, pd.DataFrame):
        return False
    if len(out_clean) != len(work) or len(out_perturbed) != len(work):
        return False
    if list(out_clean.columns) != list(out_perturbed.columns):
        return False

    for col in out_clean.columns:
        if col in (id_col, time_col):
            continue
        s_clean = out_clean[col].iloc[prefix_mask]
        s_pert = out_perturbed[col].iloc[prefix_mask]
        if pd.api.types.is_numeric_dtype(s_clean) or pd.api.types.is_numeric_dtype(s_pert):
            a_clean = pd.to_numeric(s_clean, errors="coerce").to_numpy(dtype=float)
            a_pert = pd.to_numeric(s_pert, errors="coerce").to_numpy(dtype=float)
            if not np.allclose(a_clean, a_pert, atol=1e-12, rtol=1e-9, equal_nan=True):
                return False
        else:
            if not s_clean.astype(str).equals(s_pert.astype(str)):
                return False

    return True

evaluator

Walk-forward candidate evaluator and 3-Gate Anti-Overfitting Ratchet (evolve.evaluator).

Builds directly on :meth:~scale_forecasting.sdk.Forecaster.auto by splitting the input panel into:

  1. Inner Evolution Panel ($t \le T - H_{\text{lockdown}}$): Visible to the evolutionary loop. Forecaster.auto() runs once on this inner panel to establish the baseline :class:Forecaster, :class:~scale_forecasting.auto_policy.PanelAutoProfile, cached out-of-fold predictions (oof_df), and reusable cell cache (reuse_prior_runs=True).
  2. Held-Out Lockdown Fold (last $H_{\text{lockdown}}$ steps): Completely withheld from the evolutionary loop and evaluated only once at Gate 3 on the top inner-CV challenger.

The 3-Gate Anti-Overfitting Ratchet

  • Pre-Gate (AST Security & Temporal Causality Probe): Candidate must pass :func:~scale_forecasting.evolve.sandbox.validate_candidate_ast and :func:~scale_forecasting.evolve.sandbox.verify_no_future_leakage ($y_{T-H:} \mathrel{+}= 10^6$ perturbation test).
  • Gate 1 (Inner Walk-Forward CV Lift): inner_cv_score < baseline_score.
  • Gate 2 (Diebold–Mariano & Worst-Decile Tail Guard): Paired loss differential test via :func:~scale_forecasting.diagnostics.diebold_mariano_test requires dm_pvalue <= significance_alpha (when sample size permits) and worst_decile_fva_pct >= -0.02.
  • Gate 3 (Held-Out Lockdown Fold Verification): Evaluates the winning inner-CV candidate once on the unseen Lockdown Fold and promotes (promoted = True) only if lockdown_candidate_score < lockdown_baseline_score. Otherwise ratchets back to the Forecaster.auto() baseline (promoted = False).

CandidateEvaluation dataclass

CandidateEvaluation(
    candidate_id,
    generation,
    target,
    backend,
    code,
    ast_valid,
    causal_valid,
    inner_cv_score,
    baseline_score,
    inner_fva_pct,
    dm_stat,
    dm_pvalue,
    worst_decile_fva_pct,
    gate1_passed,
    gate2_passed,
    lockdown_baseline_score,
    lockdown_candidate_score,
    gate3_passed,
    promoted,
    status,
    rejection_reason,
    wall_seconds,
    series_losses_candidate=(),
    series_losses_baseline=(),
    point_losses_candidate=(),
    point_losses_baseline=(),
)

Complete evaluation telemetry for one candidate program across all 3 ratchet gates.

to_row

to_row()

Convert candidate evaluation to a flat leaderboard row dictionary.

Source code in src/scale_forecasting/evolve/evaluator.py
def to_row(self) -> dict[str, Any]:
    """Convert candidate evaluation to a flat leaderboard row dictionary."""
    return {
        "candidate_id": self.candidate_id,
        "generation": self.generation,
        "target": self.target,
        "backend": self.backend,
        "ast_valid": self.ast_valid,
        "causal_valid": self.causal_valid,
        "inner_cv_score": (
            round(self.inner_cv_score, 6) if math.isfinite(self.inner_cv_score) else None
        ),
        "baseline_score": (
            round(self.baseline_score, 6) if math.isfinite(self.baseline_score) else None
        ),
        "inner_fva_pct": (
            round(self.inner_fva_pct, 4) if math.isfinite(self.inner_fva_pct) else 0.0
        ),
        "dm_pvalue": round(self.dm_pvalue, 6) if math.isfinite(self.dm_pvalue) else None,
        "worst_decile_fva_pct": (
            round(self.worst_decile_fva_pct, 4)
            if math.isfinite(self.worst_decile_fva_pct)
            else None
        ),
        "gate1_passed": self.gate1_passed,
        "gate2_passed": self.gate2_passed,
        "lockdown_baseline_score": (
            round(self.lockdown_baseline_score, 6)
            if math.isfinite(self.lockdown_baseline_score)
            else None
        ),
        "lockdown_candidate_score": (
            round(self.lockdown_candidate_score, 6)
            if math.isfinite(self.lockdown_candidate_score)
            else None
        ),
        "gate3_passed": self.gate3_passed,
        "promoted": self.promoted,
        "status": self.status,
        "rejection_reason": self.rejection_reason,
        "wall_seconds": round(self.wall_seconds, 4),
    }

EvolutionEvaluator

EvolutionEvaluator(
    data_df=None,
    *,
    from_runs=None,
    from_run_ids=None,
    dataset_id="scale_forecasting",
    project_id=None,
    region="us-central1",
    target="features",
    backend="alphaevolve",
    tier="first_light",
    where="local",
    horizon=None,
    significance_alpha=0.1,
    worst_decile_floor=-0.02,
    timeout_seconds=20.0,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    freq=None,
)

Evaluates candidate # EVOLVE-BLOCK programs on top of Forecaster.auto() or prior runs.

Source code in src/scale_forecasting/evolve/evaluator.py
def __init__(
    self,
    data_df: pd.DataFrame | Any = None,
    *,
    from_runs: Sequence[Any] | None = None,
    from_run_ids: Sequence[str] | None = None,
    dataset_id: str = "scale_forecasting",
    project_id: str | None = None,
    region: str = "us-central1",
    target: str = "features",
    backend: str = "alphaevolve",
    tier: str = "first_light",
    where: str = "local",
    horizon: int | None = None,
    significance_alpha: float = 0.10,
    worst_decile_floor: float = -0.02,
    timeout_seconds: float = 20.0,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    freq: str | None = None,
) -> None:
    self.target = get_target_seed(target).target
    self.backend = backend
    self.tier = tier
    self.where = where
    self.significance_alpha = significance_alpha
    self.worst_decile_floor = worst_decile_floor
    self.timeout_seconds = timeout_seconds
    self.lockdown_oof_df: pd.DataFrame = pd.DataFrame()
    self.pool_diagnostics: dict[str, Any] = {}
    self.reigning_champion_model: str = ""

    # Detect whether we are running in post-run pool mode (zero base-model refitting)
    runs_list: list[Any] = []
    if from_runs is not None:
        runs_list.extend(from_runs)
    if from_run_ids is not None:
        runs_list.extend(from_run_ids)
    if data_df is not None and not isinstance(data_df, pd.DataFrame):
        runs_list.insert(0, data_df)

    if runs_list:
        self.mode = "post_run_pool"
        self.ts_id_col = "ts_id"
        self.date_col = "ds"
        self.target_col = "y"
        pool_bundle = verify_oof_pool_compatibility(
            runs_list,
            project_id=project_id,
            dataset_id=dataset_id,
            region=region,
            horizon=horizon,
        )
        self.oof_df = pool_bundle["inner_oof_df"].copy()
        self.lockdown_oof_df = pool_bundle["lockdown_oof_df"].copy()
        self.raw_predictions_df = pool_bundle["pooled_predictions_df"].copy()
        self.reigning_champion_model = str(pool_bundle["reigning_champion_model"])
        self.pool_diagnostics = dict(pool_bundle["pool_diagnostics"])
        self.forecaster = pool_bundle.get("primary_forecaster")
        self.session = getattr(self.forecaster, "auto_session", None)
        self.profile = getattr(self.session, "profile", None)
        self.profile_dict: dict[str, Any] = (
            self.profile.to_dict()
            if self.profile is not None and hasattr(self.profile, "to_dict")
            else {
                "n_series": int(self.oof_df["ts_id"].nunique()),
                "models_pooled": self.pool_diagnostics.get("models_pooled", []),
                "reigning_champion_model": self.reigning_champion_model,
            }
        )
        self.horizon = int(
            horizon
            if horizon is not None
            else max(1, int(self.pool_diagnostics.get("lockdown_oof_timestamps", 7)))
        )
        # Reconstruct a lightweight inner_df from inner_oof_df for feature/model fallback
        self.inner_df = (
            self.oof_df.groupby(["ts_id", "ds"], as_index=False)
            .agg({"y_true": "first"})
            .rename(columns={"y_true": "y"})
        )
        self.lockdown_truth_df = (
            self.lockdown_oof_df.groupby(["ts_id", "ds"], as_index=False)
            .agg({"y_true": "first"})
            .rename(columns={"y_true": "y"})
        )
        self.lockdown_future_exog_df = self.lockdown_truth_df[["ts_id", "ds"]].copy()
    else:
        self.mode = "raw_panel"
        if not isinstance(data_df, pd.DataFrame):
            raise ConfigError(
                "EvolutionEvaluator requires a pandas DataFrame or from_runs/from_run_ids."
            )
        self.ts_id_col = ts_id_col if ts_id_col in data_df.columns else "ts_id"
        self.date_col = date_col if date_col in data_df.columns else "ds"
        self.target_col = target_col if target_col in data_df.columns else "y"

        work = data_df.copy()
        if self.ts_id_col not in work.columns:
            work[self.ts_id_col] = "series_0"
        counts = work.groupby(self.ts_id_col)[self.target_col].count()
        min_obs = int(counts.min()) if not counts.empty else 28
        self.horizon = int(horizon) if horizon is not None else max(3, min(7, min_obs // 5))

        (
            self.inner_df,
            self.lockdown_truth_df,
            self.lockdown_future_exog_df,
        ) = split_inner_and_lockdown_panel(
            work,
            self.horizon,
            ts_id_col=self.ts_id_col,
            date_col=self.date_col,
            target_col=self.target_col,
        )

        # Run Forecaster.auto() on the Inner Evolution Panel to establish cached OOF bank
        y_vals_fp = pd.to_numeric(self.inner_df[self.target_col], errors="coerce").fillna(0.0)
        cache_key = (
            len(self.inner_df),
            tuple(self.inner_df.columns),
            round(float(y_vals_fp.sum()), 6),
            round(float(y_vals_fp.iloc[0]) if len(y_vals_fp) else 0.0, 6),
            round(float(y_vals_fp.iloc[-1]) if len(y_vals_fp) else 0.0, 6),
            self.horizon,
            freq,
        )
        cached_forecaster = _BASELINE_SESSION_CACHE.get(cache_key)
        if cached_forecaster is None:
            fast_models = ["naive_seasonal", "naive_drift", "holtwinters"]
            exog_only_cols = [
                c
                for c in self.lockdown_future_exog_df.columns
                if c not in (self.ts_id_col, self.date_col, self.target_col)
                and pd.api.types.is_numeric_dtype(self.lockdown_future_exog_df[c])
            ]
            fut_exog_arg = (
                self.lockdown_future_exog_df[[self.ts_id_col, self.date_col, *exog_only_cols]]
                if exog_only_cols
                else None
            )
            cached_forecaster = auto_forecast(
                self.inner_df,
                future_df=fut_exog_arg,
                tier="wide_field",
                where="local",
                models=fast_models,
                baselines=["naive_seasonal"],
                hpo=False,
                calibration=False,
                explainability=False,
                n_folds=1,
                autofocus=False,
                horizon=self.horizon,
                ts_id_col=self.ts_id_col,
                date_col=self.date_col,
                target_col=self.target_col,
                freq=freq,
            )
            if len(_BASELINE_SESSION_CACHE) < 16:
                _BASELINE_SESSION_CACHE[cache_key] = cached_forecaster
        self.forecaster = cached_forecaster
        self.session = self.forecaster.auto_session
        self.profile = self.session.profile
        self.profile_dict = self.profile.to_dict()
        self.oof_df = self.session.oof_df.copy()
        self.raw_predictions_df = self.session.raw_predictions_df.copy()

    self.simplex_sum: float | None = self._resolve_evaluator_simplex_sum()
    self.hierarchy_spec: HierarchySpec | None = self._resolve_evaluator_hierarchy_spec()
    if (
        self.mode == "raw_panel"
        and self.hierarchy_spec is not None
        and not self.lockdown_truth_df.empty
        and "__total__" not in set(self.lockdown_truth_df[self.ts_id_col].astype(str))
    ):
        f_cfg = getattr(self.forecaster, "config", None) or getattr(
            self.forecaster, "_config", None
        )
        if (
            f_cfg is not None
            and getattr(f_cfg, "hierarchy", None) is not None
            and f_cfg.hierarchy.enabled
            and f_cfg.hierarchy.levels
            and all(
                c in self.lockdown_truth_df.columns
                for lvl in f_cfg.hierarchy.levels
                for c in (lvl if isinstance(lvl, (list, tuple)) else [lvl])
            )
        ):
            with contextlib.suppress(Exception):
                self.lockdown_truth_df, _ = build_hierarchy(self.lockdown_truth_df, f_cfg)

    # Precompute baseline inner CV losses and held-out lockdown fold losses for the target
    (
        self.baseline_score,
        self.series_losses_base,
        self.point_losses_base,
        self.lockdown_baseline_score,
    ) = self._compute_target_baselines()

evaluate_candidate_inner

evaluate_candidate_inner(code, *, generation=1)

Evaluate code through Pre-Gate (AST + Causality), Gate 1, and Gate 2.

Source code in src/scale_forecasting/evolve/evaluator.py
def evaluate_candidate_inner(
    self,
    code: str,
    *,
    generation: int = 1,
) -> CandidateEvaluation:
    """Evaluate ``code`` through Pre-Gate (AST + Causality), Gate 1, and Gate 2."""
    t0 = time.monotonic()
    cand_id = f"cand_{self.target}_g{generation:02d}"
    spec = get_target_seed(self.target)

    # Pre-Gate 1: AST Security Sandbox
    ast_res = validate_candidate_ast(code)
    if not ast_res.valid:
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=False,
            causal_valid=False,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_ast",
            rejection_reason=f"Pre-Gate AST Sandbox Violation: {ast_res.reason}",
            wall_seconds=time.monotonic() - t0,
        )

    try:
        symbol = compile_candidate_symbol(code, spec.entrypoint)
    except Exception as exc:  # noqa: BLE001 - compilation failure rejected cleanly
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=False,
            causal_valid=False,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_compile",
            rejection_reason=f"Candidate compilation error: {exc}",
            wall_seconds=time.monotonic() - t0,
        )

    # Pre-Gate 2: Temporal Causality / Future-Leakage Detector
    causal_ok = True
    if self.target in ("features", "model"):
        causal_ok = verify_no_future_leakage(
            symbol,
            self.inner_df,
            target_col=self.target_col,
            time_col=self.date_col,
            id_col=self.ts_id_col,
            horizon=self.horizon,
        )
    if not causal_ok:
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=True,
            causal_valid=False,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_leakage",
            rejection_reason=(
                "Pre-Gate Temporal Causality Violation: candidate failed "
                "verify_no_future_leakage() (perturbing y[T-H:] += 1e6 "
                "altered earlier timestamps)."
            ),
            wall_seconds=time.monotonic() - t0,
        )

    # Inner Walk-Forward CV Evaluation
    try:
        if self.target == "features":
            s_cand, p_cand = self._eval_features_ridge(
                self.inner_df, feature_fn=symbol, is_lockdown=False
            )
        elif self.target == "ensemble":
            w_cand = execute_in_sandbox(
                code,
                spec.entrypoint,
                self.oof_df.copy(),
                self.profile_dict,
                timeout_seconds=self.timeout_seconds,
            )
            if (
                not isinstance(w_cand, (Mapping, pd.DataFrame))
                or (isinstance(w_cand, Mapping) and not w_cand)
                or (isinstance(w_cand, pd.DataFrame) and w_cand.empty)
            ):
                raise ValueError(
                    "compute_evolved_weights returned empty or unsupported weights."
                )
            s_cand, p_cand = self._score_ensemble_weights_inner(w_cand)
        elif self.target == "model":
            s_cand, p_cand = self._eval_model_class(symbol, is_lockdown=False)
        elif self.target == "similarity_kernel":
            s_cand, p_cand = self._eval_similarity_kernel(
                self.inner_df, kernel_fn=symbol, is_lockdown=False
            )
        else:
            # target == "policy"
            base_w = AutoPolicyWeights.from_defaults()
            evolved_w = execute_in_sandbox(
                code,
                spec.entrypoint,
                base_w,
                timeout_seconds=self.timeout_seconds,
            )
            if isinstance(evolved_w, Mapping):
                evolved_w = AutoPolicyWeights.from_dict(evolved_w)
            if not isinstance(evolved_w, AutoPolicyWeights):
                raise ValueError("evolve_policy_weights must return AutoPolicyWeights.")
            # Weight the best models in oof_df using the evolved policy's decay/confidence
            decay = max(0.1, min(0.99, float(evolved_w.pass_decay_factor)))
            w_pol: dict[str, float] = {}
            for m_name, grp_m in self.oof_df.groupby("model_type", sort=False):
                if str(m_name).startswith("ensemble_"):
                    continue
                yt = pd.to_numeric(grp_m["y_true"], errors="coerce").to_numpy(dtype=float)
                yh = pd.to_numeric(grp_m["yhat"], errors="coerce").to_numpy(dtype=float)
                loss_m = max(1e-6, _series_wape(yt, yh))
                w_pol[str(m_name)] = 1.0 / (loss_m ** (2.0 / decay))
            tot_w = sum(w_pol.values()) or 1.0
            w_pol = {k: v / tot_w for k, v in w_pol.items()}
            s_cand, p_cand = self._score_ensemble_weights_inner(w_pol)
    except Exception as exc:  # noqa: BLE001 - runtime exception inside candidate
        return CandidateEvaluation(
            candidate_id=cand_id,
            generation=generation,
            target=self.target,
            backend=self.backend,
            code=code,
            ast_valid=True,
            causal_valid=True,
            inner_cv_score=float("inf"),
            baseline_score=self.baseline_score,
            inner_fva_pct=0.0,
            dm_stat=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=-1.0,
            gate1_passed=False,
            gate2_passed=False,
            lockdown_baseline_score=self.lockdown_baseline_score,
            lockdown_candidate_score=float("inf"),
            gate3_passed=False,
            promoted=False,
            status="rejected_runtime",
            rejection_reason=f"Candidate execution failed on Inner CV: {exc}",
            wall_seconds=time.monotonic() - t0,
        )

    stats = _compute_ratchet_stats(
        s_cand,
        self.series_losses_base,
        p_cand,
        self.point_losses_base,
        significance_alpha=self.significance_alpha,
        worst_decile_floor=self.worst_decile_floor,
    )
    status = (
        "passed_inner_gates"
        if (stats["gate1_passed"] and stats["gate2_passed"])
        else ("rejected_gate1" if not stats["gate1_passed"] else "rejected_gate2")
    )
    return CandidateEvaluation(
        candidate_id=cand_id,
        generation=generation,
        target=self.target,
        backend=self.backend,
        code=code,
        ast_valid=True,
        causal_valid=True,
        inner_cv_score=float(stats["inner_cv_score"]),
        baseline_score=self.baseline_score,
        inner_fva_pct=float(stats["inner_fva_pct"]),
        dm_stat=float(stats["dm_stat"]),
        dm_pvalue=float(stats["dm_pvalue"]),
        worst_decile_fva_pct=float(stats["worst_decile_fva_pct"]),
        gate1_passed=bool(stats["gate1_passed"]),
        gate2_passed=bool(stats["gate2_passed"]),
        lockdown_baseline_score=self.lockdown_baseline_score,
        lockdown_candidate_score=float("nan"),
        gate3_passed=False,
        promoted=False,
        status=status,
        rejection_reason=stats["rejection_reason"],
        wall_seconds=time.monotonic() - t0,
        series_losses_candidate=tuple(s_cand),
        series_losses_baseline=tuple(self.series_losses_base),
        point_losses_candidate=tuple(p_cand),
        point_losses_baseline=tuple(self.point_losses_base),
    )

evaluate_lockdown_gate3

evaluate_lockdown_gate3(cand_eval)

Evaluate the winning inner-CV candidate once on the Held-Out Lockdown Fold.

Source code in src/scale_forecasting/evolve/evaluator.py
def evaluate_lockdown_gate3(
    self,
    cand_eval: CandidateEvaluation,
) -> CandidateEvaluation:
    """Evaluate the winning inner-CV candidate **once** on the Held-Out Lockdown Fold."""
    t0 = time.monotonic()
    spec = get_target_seed(self.target)
    try:
        symbol = compile_candidate_symbol(cand_eval.code, spec.entrypoint)
        if self.target == "features":
            s_lock, _ = self._eval_features_ridge(
                self.inner_df,
                feature_fn=symbol,
                is_lockdown=True,
                lockdown_truth_df=self.lockdown_truth_df,
            )
            lock_cand_score = float(np.mean(s_lock)) if s_lock else float("inf")
        elif self.target == "ensemble":
            w_cand = symbol(self.oof_df.copy(), self.profile_dict)
            lock_cand_score = self._score_ensemble_weights_lockdown(w_cand)
        elif self.target == "model":
            s_lock, _ = self._eval_model_class(symbol, is_lockdown=True)
            lock_cand_score = float(np.mean(s_lock)) if s_lock else float("inf")
        elif self.target == "similarity_kernel":
            s_lock, _ = self._eval_similarity_kernel(
                self.inner_df,
                kernel_fn=symbol,
                is_lockdown=True,
                lockdown_truth_df=self.lockdown_truth_df,
            )
            lock_cand_score = float(np.mean(s_lock)) if s_lock else float("inf")
        else:
            base_w = AutoPolicyWeights.from_defaults()
            evolved_w = symbol(base_w)
            if isinstance(evolved_w, Mapping):
                evolved_w = AutoPolicyWeights.from_dict(evolved_w)
            decay = max(0.1, min(0.99, float(evolved_w.pass_decay_factor)))
            w_pol: dict[str, float] = {}
            for m_name, grp_m in self.oof_df.groupby("model_type", sort=False):
                if str(m_name).startswith("ensemble_"):
                    continue
                yt = pd.to_numeric(grp_m["y_true"], errors="coerce").to_numpy(dtype=float)
                yh = pd.to_numeric(grp_m["yhat"], errors="coerce").to_numpy(dtype=float)
                loss_m = max(1e-6, _series_wape(yt, yh))
                w_pol[str(m_name)] = 1.0 / (loss_m ** (2.0 / decay))
            tot_w = sum(w_pol.values()) or 1.0
            w_pol = {k: v / tot_w for k, v in w_pol.items()}
            lock_cand_score = self._score_ensemble_weights_lockdown(w_pol)
    except Exception as exc:  # noqa: BLE001 - lockdown runtime failure rejects at Gate 3
        return CandidateEvaluation(
            **{
                **cand_eval.__dict__,
                "lockdown_candidate_score": float("inf"),
                "gate3_passed": False,
                "promoted": False,
                "status": "rejected_gate3",
                "rejection_reason": (
                    "Gate 3 (Held-Out Lockdown Fold): "
                    f"execution failed on lockdown fold ({exc})."
                ),
                "wall_seconds": cand_eval.wall_seconds + (time.monotonic() - t0),
            }
        )

    gate3_passed = bool(
        math.isfinite(lock_cand_score) and lock_cand_score < self.lockdown_baseline_score - 1e-9
    )
    promoted = bool(cand_eval.gate1_passed and cand_eval.gate2_passed and gate3_passed)
    if promoted:
        status = "promoted_champion"
        rejection_reason = None
    elif not cand_eval.gate1_passed or not cand_eval.gate2_passed:
        status = cand_eval.status
        rejection_reason = cand_eval.rejection_reason
    else:
        status = "rejected_gate3"
        rejection_reason = (
            f"Gate 3 (Held-Out Lockdown Fold): candidate improved inner CV "
            f"({cand_eval.inner_cv_score:.4f} < {cand_eval.baseline_score:.4f}) "
            f"but degraded or failed to beat baseline on the unseen lockdown fold "
            f"({lock_cand_score:.4f} >= {self.lockdown_baseline_score:.4f}). "
            f"Ratcheted back to Forecaster.auto() baseline."
        )

    return CandidateEvaluation(
        **{
            **cand_eval.__dict__,
            "lockdown_candidate_score": lock_cand_score,
            "gate3_passed": gate3_passed,
            "promoted": promoted,
            "status": status,
            "rejection_reason": rejection_reason,
            "wall_seconds": cand_eval.wall_seconds + (time.monotonic() - t0),
        }
    )

materialize_ensemble_predictions

materialize_ensemble_predictions(
    weights, *, model_label="ensemble_evolved"
)

Materialize blended forward forecasts with empirical conformal 80% intervals.

Source code in src/scale_forecasting/evolve/evaluator.py
def materialize_ensemble_predictions(
    self,
    weights: Any,
    *,
    model_label: str = "ensemble_evolved",
) -> pd.DataFrame:
    """Materialize blended forward forecasts with empirical conformal 80% intervals."""
    source_preds = self.raw_predictions_df.copy()
    date_col = "forecast_date"
    if source_preds.empty and not self.lockdown_oof_df.empty:
        source_preds = self.lockdown_oof_df.copy()
        if "forecast_date" not in source_preds.columns and "ds" in source_preds.columns:
            source_preds["forecast_date"] = source_preds["ds"]
    if source_preds.empty:
        return pd.DataFrame(
            columns=["ts_id", "forecast_date", "yhat", "yhat_lower", "yhat_upper", "model_type"]
        )

    avail_pred_models = sorted(source_preds["model_type"].astype(str).unique())
    eff_weights = weights
    if (
        isinstance(weights, Mapping)
        and len(weights) == 1
        and not isinstance(next(iter(weights.values())), Mapping)
        and str(next(iter(weights.keys()))) not in avail_pred_models
        and avail_pred_models
    ):
        only_key = str(next(iter(weights.keys())))
        base_prefix = only_key.split("@", 1)[0]
        matched_m = [
            m for m in avail_pred_models if m == base_prefix or m.startswith(f"{base_prefix}_")
        ]
        base_m = (
            matched_m
            or [m for m in avail_pred_models if not m.startswith("ensemble_")]
            or avail_pred_models
        )
        eff_weights = {m: 1.0 / len(base_m) for m in base_m}

    blended_preds = _blend_frame_with_series_weights(
        source_preds,
        eff_weights,
        date_col=date_col,
        simplex_sum=self.simplex_sum,
        hierarchy_spec=self.hierarchy_spec,
    )
    if blended_preds.empty:
        return pd.DataFrame(
            columns=["ts_id", "forecast_date", "yhat", "yhat_lower", "yhat_upper", "model_type"]
        )

    # Compute empirical 80th percentile absolute residual per series on OOF
    oof_date_col = "ds" if "ds" in self.oof_df.columns else "forecast_date"
    blended_oof = _blend_frame_with_series_weights(
        self.oof_df,
        weights,
        date_col=oof_date_col,
        simplex_sum=self.simplex_sum,
        hierarchy_spec=self.hierarchy_spec,
    )
    q80_by_ts: dict[str, float] = {}
    if not blended_oof.empty and "y_true" in blended_oof.columns:
        for tid, grp_o in blended_oof.groupby("ts_id", sort=False):
            abs_res = np.abs(
                pd.to_numeric(grp_o["y_true"], errors="coerce").to_numpy(dtype=float)
                - pd.to_numeric(grp_o["yhat_blend"], errors="coerce").to_numpy(dtype=float)
            )
            finite_res = abs_res[np.isfinite(abs_res)]
            if len(finite_res) > 0:
                q80_by_ts[str(tid)] = float(np.quantile(finite_res, 0.80))

    out_rows: list[dict[str, Any]] = []
    for _, row in blended_preds.iterrows():
        tid_s = str(row["ts_id"])
        yh_val = float(row["yhat_blend"])
        q80 = q80_by_ts.get(tid_s, max(1e-3, 0.10 * abs(yh_val)))
        low_val = (
            float(row["yhat_lower_blend"])
            if "yhat_lower_blend" in row and pd.notna(row["yhat_lower_blend"])
            else (yh_val - q80)
        )
        high_val = (
            float(row["yhat_upper_blend"])
            if "yhat_upper_blend" in row and pd.notna(row["yhat_upper_blend"])
            else (yh_val + q80)
        )
        # Enforce conformal coverage floor from OOF residuals
        half_w = max(0.5 * abs(high_val - low_val), q80)
        out_rows.append(
            {
                "ts_id": tid_s,
                "forecast_date": row[date_col],
                "yhat": yh_val,
                "yhat_lower": yh_val - half_w,
                "yhat_upper": yh_val + half_w,
                "model_type": model_label,
            }
        )
    out_df = pd.DataFrame(out_rows)
    if self.hierarchy_spec is not None and not out_df.empty:
        out_df = _project_blended_hierarchy(
            out_df,
            self.hierarchy_spec,
            date_col="forecast_date",
            value_col="yhat",
        )
    if self.simplex_sum is not None and float(self.simplex_sum) > 0.0 and not out_df.empty:
        out_df = enforce_simplex_closure(
            out_df,
            value_col="yhat",
            simplex_sum=float(self.simplex_sum),
            ts_id_col="ts_id",
            date_col="forecast_date",
        )
    return out_df

split_inner_and_lockdown_panel

split_inner_and_lockdown_panel(
    df,
    horizon,
    *,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
)

Split a historical panel into (inner_df, lockdown_truth_df, lockdown_future_exog_df).

  • inner_df: rows $t \le T - H_{\text{lockdown}}$ per series (visible to evolution).
  • lockdown_truth_df: last $H_{\text{lockdown}}$ historical rows per series with true y (withheld for Gate 3 verification).
  • lockdown_future_exog_df: exogenous covariate rows for the lockdown window with y removed so lockdown predictions cannot observe held-out targets.
Source code in src/scale_forecasting/evolve/evaluator.py
def split_inner_and_lockdown_panel(
    df: pd.DataFrame,
    horizon: int,
    *,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    """Split a historical panel into `(inner_df, lockdown_truth_df, lockdown_future_exog_df)`.

    - ``inner_df``: rows $t \\le T - H_{\\text{lockdown}}$ per series (visible to evolution).
    - ``lockdown_truth_df``: last $H_{\\text{lockdown}}$ historical rows per series with true
      ``y`` (withheld for Gate 3 verification).
    - ``lockdown_future_exog_df``: exogenous covariate rows for the lockdown window with ``y``
      removed so lockdown predictions cannot observe held-out targets.
    """
    work = df.copy()
    if ts_id_col not in work.columns:
        work[ts_id_col] = "series_0"
    y_num = pd.to_numeric(work[target_col], errors="coerce")
    hist = work[y_num.notna()].sort_values([ts_id_col, date_col]).reset_index(drop=True)
    if hist.empty:
        raise ConfigError("Input panel has no valid numeric target rows.")

    h = max(1, int(horizon))
    inner_parts: list[pd.DataFrame] = []
    lock_parts: list[pd.DataFrame] = []

    for _, grp in hist.groupby(ts_id_col, sort=False):
        n_obs = len(grp)
        eff_h = min(h, max(2, n_obs // 4))
        inner_parts.append(grp.iloc[:-eff_h])
        lock_parts.append(grp.iloc[-eff_h:])

    inner_df = pd.concat(inner_parts, ignore_index=True)
    lockdown_truth_df = pd.concat(lock_parts, ignore_index=True)
    exog_cols = [c for c in lockdown_truth_df.columns if c != target_col]
    lockdown_future_exog_df = lockdown_truth_df[exog_cols].copy()
    return inner_df, lockdown_truth_df, lockdown_future_exog_df

verify_oof_pool_compatibility

verify_oof_pool_compatibility(
    runs,
    *,
    project_id=None,
    dataset_id="scale_forecasting",
    region="us-central1",
    horizon=None,
)

Verify OOF & horizon alignment across runs, disambiguate colliding models, and split.

Verifies how borrowing interacts with backtest, hpo, and ensemble: - Requires non-empty overlapping (ts_id, ds) out-of-fold rows across all runs (and overlapping (ts_id, forecast_date) horizon grids when forward predictions are present), raising :class:~scale_forecasting.errors.ConfigError when disjoint. - When multiple runs contain the same model_type, compares their aligned OOF yhat trajectories: identical trajectories (same model_spec_hash) are deduplicated, whereas distinct trajectories (different HPO winner, model_params, or ensemble pool) are disambiguated as <model_type>@<run_short_id>. - Splits the pooled oof_df temporally per series into inner_oof_df (for candidate synthesis and Gates 1 & 2) and lockdown_oof_df (withheld for Gate 3).

Source code in src/scale_forecasting/evolve/evaluator.py
def verify_oof_pool_compatibility(
    runs: Sequence[Any],
    *,
    project_id: str | None = None,
    dataset_id: str = "scale_forecasting",
    region: str = "us-central1",
    horizon: int | None = None,
) -> dict[str, Any]:
    """Verify OOF & horizon alignment across ``runs``, disambiguate colliding models, and split.

    Verifies how borrowing interacts with ``backtest``, ``hpo``, and ``ensemble``:
    - Requires non-empty overlapping ``(ts_id, ds)`` out-of-fold rows across all runs (and
      overlapping ``(ts_id, forecast_date)`` horizon grids when forward predictions are present),
      raising :class:`~scale_forecasting.errors.ConfigError` when disjoint.
    - When multiple runs contain the same ``model_type``, compares their aligned OOF ``yhat``
      trajectories: identical trajectories (same ``model_spec_hash``) are deduplicated, whereas
      distinct trajectories (different HPO winner, ``model_params``, or ensemble pool) are
      disambiguated as ``<model_type>@<run_short_id>``.
    - Splits the pooled ``oof_df`` temporally per series into ``inner_oof_df`` (for candidate
      synthesis and Gates 1 & 2) and ``lockdown_oof_df`` (withheld for Gate 3).
    """
    if not runs:
        raise ConfigError("verify_oof_pool_compatibility requires at least one run.")

    extracted = [
        _extract_run_artifacts(
            r,
            idx=i,
            project_id=project_id,
            dataset_id=dataset_id,
            region=region,
        )
        for i, r in enumerate(runs)
    ]

    # Ensure unique short_ids when multiple runs are pooled
    seen_shorts: set[str] = set()
    for i, item in enumerate(extracted):
        s_id = str(item["short_id"])
        if s_id in seen_shorts:
            s_id = f"{s_id}_{i + 1}"
            item["short_id"] = s_id
        seen_shorts.add(s_id)

    # 1. Verify overlapping (ts_id, ds) OOF keys across all runs
    series_sets = [set(item["oof_df"]["ts_id"].unique()) for item in extracted]
    common_series = sorted(set.intersection(*series_sets)) if series_sets else []
    if not common_series:
        raise ConfigError(
            "verify_oof_pool_compatibility failed: pooled runs share zero overlapping ts_id series."
        )

    oof_key_sets = [
        set(zip(item["oof_df"]["ts_id"], item["oof_df"]["ds"], strict=False)) for item in extracted
    ]
    common_oof_keys = set.intersection(*oof_key_sets) if oof_key_sets else set()
    if not common_oof_keys:
        raise ConfigError(
            "verify_oof_pool_compatibility failed: pooled runs share zero overlapping "
            "(ts_id, ds) out-of-fold timestamps."
        )

    # 2. Verify overlapping (ts_id, forecast_date) forward prediction keys when present
    non_empty_preds = [
        item["predictions_df"] for item in extracted if not item["predictions_df"].empty
    ]
    common_pred_keys: set[tuple[Any, Any]] | None = None
    if len(non_empty_preds) >= 2:
        pred_key_sets = [
            set(zip(p["ts_id"], p["forecast_date"], strict=False)) for p in non_empty_preds
        ]
        common_pred_keys = set.intersection(*pred_key_sets)
        if not common_pred_keys:
            raise ConfigError(
                "verify_oof_pool_compatibility failed: pooled runs share zero overlapping "
                "(ts_id, forecast_date) forward forecast horizon rows."
            )

    # 3. Filter each run to the common grid and disambiguate vs. deduplicate models across runs
    model_run_counts: dict[str, int] = {}
    for item in extracted:
        for m in item["oof_df"]["model_type"].unique():
            model_run_counts[str(m)] = model_run_counts.get(str(m), 0) + 1

    accepted_oof_by_model: dict[str, np.ndarray] = {}
    accepted_short_by_model: dict[str, str] = {}
    first_occurrence_frames: dict[str, tuple[pd.DataFrame, pd.DataFrame]] = {}
    deduplicated_models: list[str] = []
    disambiguated_models: list[str] = []

    pooled_oof_parts: list[pd.DataFrame] = []
    pooled_pred_parts: list[pd.DataFrame] = []

    for item in extracted:
        s_id = str(item["short_id"])
        oof_i = item["oof_df"].copy()
        oof_keys = list(zip(oof_i["ts_id"], oof_i["ds"], strict=False))
        oof_i = oof_i[[k in common_oof_keys for k in oof_keys]].copy()

        pred_i = item["predictions_df"].copy()
        if not pred_i.empty and common_pred_keys is not None:
            p_keys = list(zip(pred_i["ts_id"], pred_i["forecast_date"], strict=False))
            pred_i = pred_i[[k in common_pred_keys for k in p_keys]].copy()

        for m_name, grp_m in oof_i.groupby("model_type", sort=False):
            m_str = str(m_name)
            grp_sorted = grp_m.sort_values(["ts_id", "ds"]).reset_index(drop=True)
            yhat_vec = grp_sorted["yhat"].to_numpy(dtype=float)
            pred_m = (
                pred_i[pred_i["model_type"] == m_str].copy() if not pred_i.empty else pd.DataFrame()
            )

            if model_run_counts.get(m_str, 1) == 1:
                pooled_oof_parts.append(grp_sorted)
                if not pred_m.empty:
                    pooled_pred_parts.append(pred_m)
                continue

            if m_str not in accepted_oof_by_model:
                accepted_oof_by_model[m_str] = yhat_vec
                accepted_short_by_model[m_str] = s_id
                first_occurrence_frames[m_str] = (grp_sorted, pred_m)
                pooled_oof_parts.append(grp_sorted)
                if not pred_m.empty:
                    pooled_pred_parts.append(pred_m)
                continue

            prev_vec = accepted_oof_by_model[m_str]
            if len(prev_vec) == len(yhat_vec) and np.allclose(
                prev_vec, yhat_vec, atol=1e-6, equal_nan=True
            ):
                if m_str not in deduplicated_models:
                    deduplicated_models.append(m_str)
                continue

            # Disambiguate both the first occurrence (if not yet renamed) and this occurrence
            prev_short = accepted_short_by_model[m_str]
            first_oof, first_pred = first_occurrence_frames[m_str]
            first_new_name = f"{m_str}@{prev_short}"
            first_oof["model_type"] = first_new_name
            if not first_pred.empty:
                first_pred["model_type"] = first_new_name
            if first_new_name not in disambiguated_models:
                disambiguated_models.append(first_new_name)

            curr_new_name = f"{m_str}@{s_id}"
            grp_sorted = grp_sorted.copy()
            grp_sorted["model_type"] = curr_new_name
            pooled_oof_parts.append(grp_sorted)
            if not pred_m.empty:
                pred_m = pred_m.copy()
                pred_m["model_type"] = curr_new_name
                pooled_pred_parts.append(pred_m)
            if curr_new_name not in disambiguated_models:
                disambiguated_models.append(curr_new_name)

    pooled_oof_df = pd.concat(pooled_oof_parts, ignore_index=True)
    pooled_predictions_df = (
        pd.concat(pooled_pred_parts, ignore_index=True) if pooled_pred_parts else pd.DataFrame()
    )

    # 4. Split pooled_oof_df temporally per series into Inner Evolution OOF & Lockdown OOF
    inner_parts: list[pd.DataFrame] = []
    lock_parts: list[pd.DataFrame] = []
    inner_ts_count = 0
    lock_ts_count = 0

    for _, grp_s in pooled_oof_df.groupby("ts_id", sort=True):
        unique_ds = sorted(grp_s["ds"].unique())
        n_ds = len(unique_ds)
        if n_ds >= 3:
            default_lock = max(1, n_ds // 3)
            n_lock = min(
                default_lock,
                int(horizon) if horizon is not None else default_lock,
                n_ds - 2,
            )
            n_lock = max(1, n_lock)
            in_dates = set(unique_ds[:-n_lock])
            lk_dates = set(unique_ds[-n_lock:])
        elif n_ds == 2:
            in_dates = {unique_ds[0]}
            lk_dates = {unique_ds[1]}
        else:
            in_dates = set(unique_ds)
            lk_dates = set(unique_ds)

        inner_ts_count = max(inner_ts_count, len(in_dates))
        lock_ts_count = max(lock_ts_count, len(lk_dates))
        inner_parts.append(grp_s[grp_s["ds"].isin(in_dates)])
        lock_parts.append(grp_s[grp_s["ds"].isin(lk_dates)])

    inner_oof_df = pd.concat(inner_parts, ignore_index=True)
    lockdown_oof_df = pd.concat(lock_parts, ignore_index=True)

    # 5. Evaluate every model and built-in ensemble_* row to identify reigning_champion_model
    models_pooled = sorted(pooled_oof_df["model_type"].astype(str).unique())
    model_inner_scores: dict[str, float] = {}
    for m_name, grp_m in inner_oof_df.groupby("model_type", sort=False):
        s_losses = [
            _series_wape(
                grp_s["y_true"].to_numpy(dtype=float),
                grp_s["yhat"].to_numpy(dtype=float),
            )
            for _, grp_s in grp_m.groupby("ts_id", sort=True)
        ]
        if s_losses:
            model_inner_scores[str(m_name)] = float(np.mean(s_losses))

    reigning_champ = (
        min(model_inner_scores, key=lambda k: model_inner_scores[k])
        if model_inner_scores
        else (models_pooled[0] if models_pooled else "ensemble_mean")
    )

    source_run_ids = [str(item["run_id"]) for item in extracted]
    pool_diagnostics: dict[str, Any] = {
        "mode": "post_run_pool",
        "source_run_ids": source_run_ids,
        "models_pooled": models_pooled,
        "deduplicated_models": sorted(deduplicated_models),
        "disambiguated_models": sorted(disambiguated_models),
        "reigning_champion_model": reigning_champ,
        "reigning_champion_inner_score": round(
            float(model_inner_scores.get(reigning_champ, float("nan"))), 6
        ),
        "common_series_count": len(common_series),
        "inner_oof_timestamps": inner_ts_count,
        "inner_oof_Timestamps": inner_ts_count,
        "lockdown_oof_timestamps": lock_ts_count,
        "borrow_interactions": {
            "backtest": "requires identical (ts_id, ds) evaluation timestamps across pooled runs",
            "hpo": (
                "models with identical OOF trajectories are deduplicated; "
                "models with distinct HPO/config fits are disambiguated as <model>@<run_short_id>"
            ),
            "ensemble": "never borrowed passively; re-synthesized across all pooled models",
        },
    }

    return {
        "source_run_ids": source_run_ids,
        "pooled_oof_df": pooled_oof_df,
        "inner_oof_df": inner_oof_df,
        "lockdown_oof_df": lockdown_oof_df,
        "pooled_predictions_df": pooled_predictions_df,
        "reigning_champion_model": reigning_champ,
        "model_inner_scores": model_inner_scores,
        "pool_diagnostics": pool_diagnostics,
        "primary_forecaster": extracted[0].get("forecaster"),
    }

runner

End-to-end evolutionary runner (EvolveConfig, EvolveResult, run_evolution).

Orchestrates the closed-loop evolutionary cycle on top of :meth:~scale_forecasting.sdk.Forecaster.auto:

  1. Pre-Flight Entitlement Check: When backend="alphaevolve" (the default), calls :func:~scale_forecasting.evolve.client.probe_alphaevolve_access before any backtests run so projects without Gemini Enterprise + AlphaEvolve entitlement fail fast with actionable guidance pointing to Forecaster.auto() and the backend="vertex_gemini" backup.
  2. Temporal Lockdown Split & Forecaster.auto() Baseline: Withholds the last $H_{\text{lockdown}}$ steps per series as the unseen Lockdown Fold and runs Forecaster.auto() on the Inner Evolution Panel ($t \le T - H_{\text{lockdown}}$).
  3. Iterative Mutation & Pre-Gate / Gate 1 / Gate 2 Filtering: Generates up to max_evaluations candidate # EVOLVE-BLOCK programs via alphaevolve, vertex_gemini, or mock, checking each through the AST security sandbox, the $+10^6$ temporal lookahead detector, Gate 1 (inner CV lift), and Gate 2 (Diebold–Mariano $p$-value + worst-decile FVA guard).
  4. Gate 3 (Held-Out Lockdown Fold Promotion Ratchet): Evaluates the winning inner-CV challenger once on the unseen Lockdown Fold and promotes promoted = True only when lockdown_candidate_score < lockdown_baseline_score.

EvolveConfig dataclass

EvolveConfig(
    target="features",
    backend="alphaevolve",
    tier="deep_sky",
    where="local",
    horizon=None,
    max_evaluations=10,
    significance_alpha=0.1,
    worst_decile_floor=-0.02,
    project_id=None,
    location="global",
    region="us-central1",
    model_name=DEFAULT_GEMINI_MODEL,
    export_path=None,
    random_seed=42,
    decision_metric=None,
    timeout_seconds=20.0,
    dry_run=False,
    mock_candidates=None,
    candidate_programs=None,
    lockdown_override_score=None,
    from_runs=None,
    from_run_ids=None,
    dataset_id="scale_forecasting",
)

Configuration for an opt-in :func:run_evolution / :meth:Forecaster.evolve session.

model_dump

model_dump(**_kwargs)

Pydantic-compatible alias for :meth:to_dict.

Source code in src/scale_forecasting/evolve/runner.py
def model_dump(self, **_kwargs: Any) -> dict[str, Any]:
    """Pydantic-compatible alias for :meth:`to_dict`."""
    return self.to_dict()

model_validate classmethod

model_validate(obj)

Validate a dictionary or :class:EvolveConfig instance.

Source code in src/scale_forecasting/evolve/runner.py
@classmethod
def model_validate(cls, obj: EvolveConfig | Mapping[str, Any]) -> EvolveConfig:
    """Validate a dictionary or :class:`EvolveConfig` instance."""
    if isinstance(obj, cls):
        return obj
    if isinstance(obj, Mapping):
        valid_keys = {f.name for f in dataclasses.fields(cls)}
        filtered = {k: v for k, v in obj.items() if k in valid_keys}
        if (
            "candidates" in obj
            and "mock_candidates" not in filtered
            and obj["candidates"] is not None
        ):
            filtered["mock_candidates"] = tuple(obj["candidates"])
        return cls(**filtered)
    raise ConfigError(f"Cannot coerce {type(obj).__name__} into EvolveConfig.")

to_dict

to_dict()

Serialize configuration to a plain JSON-friendly dictionary.

Source code in src/scale_forecasting/evolve/runner.py
def to_dict(self) -> dict[str, Any]:
    """Serialize configuration to a plain JSON-friendly dictionary."""
    raw = dataclasses.asdict(self)
    if raw.get("mock_candidates") is not None:
        raw["mock_candidates"] = list(raw["mock_candidates"])
    if raw.get("from_runs") is not None:
        raw["from_runs"] = list(raw["from_runs"])
    if raw.get("from_run_ids") is not None:
        raw["from_run_ids"] = list(raw["from_run_ids"])
    return raw

EvolveResult dataclass

EvolveResult(
    target,
    backend_used,
    promoted,
    rejection_reason,
    baseline_score,
    inner_cv_score,
    lockdown_baseline_score,
    lockdown_candidate_score,
    fva_pct,
    dm_pvalue,
    worst_decile_fva_pct,
    champion_code,
    export_path,
    leaderboard_df,
    forecaster=None,
    assessment=None,
    evaluations_run=0,
    wall_seconds=0.0,
    candidate_code="",
    diagnostics=dict(),
    predictions_df=None,
    model_name=DEFAULT_GEMINI_MODEL,
)

Outcome of an evolutionary run governed by the 3-Gate Anti-Overfitting Ratchet.

emit_airflow_dag

emit_airflow_dag(
    output_path=None, schedule="@monthly", *, dag_id=None
)

Render a standalone Cloud Composer 3 / Airflow DAG scheduling periodic evolution.

If output_path is provided, writes the DAG Python source to output_path and returns the rendered DAG source code string.

Source code in src/scale_forecasting/evolve/runner.py
    def emit_airflow_dag(
        self,
        output_path: str | Path | None = None,
        schedule: str = "@monthly",
        *,
        dag_id: str | None = None,
    ) -> str:
        """Render a standalone Cloud Composer 3 / Airflow DAG scheduling periodic evolution.

        If ``output_path`` is provided, writes the DAG Python source to ``output_path`` and returns
        the rendered DAG source code string.
        """
        import tempfile

        eff_dag_id = dag_id or f"scale_forecasting_evolve_{self.target}"
        default_export = Path(tempfile.gettempdir()) / f"evolved_{self.target}.py"
        export_target = self.export_path or str(default_export)
        dag_source = f'''"""Airflow DAG for scheduled scale_forecasting.evolve ({self.target})."""

from __future__ import annotations

from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash import BashOperator

DEFAULT_ARGS = {{
    "owner": "scale-forecasting",
    "depends_on_past": False,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
}}

with DAG(
    dag_id="{eff_dag_id}",
    default_args=DEFAULT_ARGS,
    description=(
        "Scheduled 3-Gate Anti-Overfitting evolution for "
        "target={self.target} (backend={self.backend_used}, model={self.model_name})"
    ),
    schedule="{schedule}",
    start_date=datetime(2026, 1, 1),
    catchup=False,
    tags=["scale-forecasting", "evolve", "{self.target}", "{self.backend_used}"],
) as dag:
    evolve_and_verify = BashOperator(
        task_id="evolve_{self.target}_with_3gate_ratchet",
        bash_command=(
            "python -m scale_forecasting.evolve "
            "--target {self.target} "
            "--backend {self.backend_used} "
            "--model-name {self.model_name} "
            "--export-path {export_target}"
        ),
    )
'''
        if output_path is not None:
            out_p = Path(output_path)
            out_p.parent.mkdir(parents=True, exist_ok=True)
            out_p.write_text(dag_source, encoding="utf-8")
        return dag_source

summary

summary()

Return a concise human-readable summary of the 3-Gate Ratchet verdict.

Source code in src/scale_forecasting/evolve/runner.py
def summary(self) -> str:
    """Return a concise human-readable summary of the 3-Gate Ratchet verdict."""
    verdict = (
        "PROMOTED (Passed Gates 1, 2 & 3)"
        if self.promoted
        else f"RATCHETED TO BASELINE ({self.rejection_reason})"
    )
    return (
        f"EvolveResult(target='{self.target}', backend='{self.backend_used}', "
        f"verdict='{verdict}', baseline={self.baseline_score:.4f}, "
        f"inner_cv={self.inner_cv_score:.4f}, "
        f"lockdown_base={self.lockdown_baseline_score:.4f}, "
        f"lockdown_cand={self.lockdown_candidate_score:.4f}, "
        f"fva_pct={self.fva_pct:+.2f}%, dm_pvalue={self.dm_pvalue:.4f}, "
        f"worst_decile_fva={self.worst_decile_fva_pct:+.4f}, "
        f"wall_s={self.wall_seconds:.2f}s)"
    )

to_dict

to_dict()

Serialize result summary and leaderboard to a JSON-compatible dictionary.

Source code in src/scale_forecasting/evolve/runner.py
def to_dict(self) -> dict[str, Any]:
    """Serialize result summary and leaderboard to a JSON-compatible dictionary."""
    return {
        "target": self.target,
        "backend_used": self.backend_used,
        "model_name": self.model_name,
        "promoted": self.promoted,
        "rejection_reason": self.rejection_reason,
        "baseline_score": (
            round(self.baseline_score, 6) if math.isfinite(self.baseline_score) else None
        ),
        "inner_cv_score": (
            round(self.inner_cv_score, 6) if math.isfinite(self.inner_cv_score) else None
        ),
        "lockdown_baseline_score": (
            round(self.lockdown_baseline_score, 6)
            if math.isfinite(self.lockdown_baseline_score)
            else None
        ),
        "lockdown_candidate_score": (
            round(self.lockdown_candidate_score, 6)
            if math.isfinite(self.lockdown_candidate_score)
            else None
        ),
        "fva_pct": round(self.fva_pct, 4) if math.isfinite(self.fva_pct) else 0.0,
        "dm_pvalue": round(self.dm_pvalue, 6) if math.isfinite(self.dm_pvalue) else None,
        "worst_decile_fva_pct": (
            round(self.worst_decile_fva_pct, 4)
            if math.isfinite(self.worst_decile_fva_pct)
            else None
        ),
        "evaluations_run": self.evaluations_run,
        "wall_seconds": round(self.wall_seconds, 3),
        "export_path": self.export_path,
        "champion_code": self.champion_code,
        "diagnostics": self.diagnostics,
        "leaderboard": self.leaderboard_df.to_dict(orient="records"),
    }

run_evolution

run_evolution(
    data=None,
    config=None,
    *,
    from_runs=None,
    from_run_ids=None,
    dataset_id=None,
    target=None,
    backend=None,
    tier=None,
    where=None,
    horizon=None,
    max_evaluations=None,
    significance_alpha=None,
    worst_decile_floor=None,
    project_id=None,
    location=None,
    region=None,
    model_name=None,
    export_path=None,
    random_seed=None,
    decision_metric=None,
    timeout_seconds=None,
    dry_run=None,
    mock_candidates=None,
    candidates=None,
    lockdown_override_score=None,
    genai_client=None,
    alphaevolve_http_request=None,
    http_get=None,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    freq=None,
)

Run opt-in evolutionary code synthesis on top of Forecaster.auto() or prior runs.

Source code in src/scale_forecasting/evolve/runner.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
def run_evolution(
    data: pd.DataFrame | str | Any | None = None,
    config: EvolveConfig | Mapping[str, Any] | None = None,
    *,
    from_runs: Sequence[Any] | None = None,
    from_run_ids: Sequence[str] | None = None,
    dataset_id: str | None = None,
    target: str | None = None,
    backend: str | None = None,
    tier: str | None = None,
    where: str | None = None,
    horizon: int | None = None,
    max_evaluations: int | None = None,
    significance_alpha: float | None = None,
    worst_decile_floor: float | None = None,
    project_id: str | None = None,
    location: str | None = None,
    region: str | None = None,
    model_name: str | None = None,
    export_path: str | Path | None = None,
    random_seed: int | None = None,
    decision_metric: str | None = None,
    timeout_seconds: float | None = None,
    dry_run: bool | None = None,
    mock_candidates: Sequence[str] | None = None,
    candidates: Sequence[str] | None = None,
    lockdown_override_score: float | None = None,
    genai_client: Any = None,
    alphaevolve_http_request: Callable[..., dict[str, Any]] | None = None,
    http_get: Callable[..., Any] | None = None,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    freq: str | None = None,
) -> EvolveResult:
    """Run opt-in evolutionary code synthesis on top of ``Forecaster.auto()`` or prior runs."""
    t_start = time.monotonic()
    base_dict: dict[str, Any] = {}
    if config is not None:
        base_dict = EvolveConfig.model_validate(config).to_dict()

    # When evolving directly on prior runs or an executed Forecaster without an explicit target,
    # default to "ensemble" (post-run pool evolution without base-model refitting).
    has_post_run_inputs = (
        from_runs is not None
        or from_run_ids is not None
        or bool(base_dict.get("from_runs"))
        or bool(base_dict.get("from_run_ids"))
        or (data is not None and not isinstance(data, (pd.DataFrame, str)))
    )
    if (
        has_post_run_inputs
        and target is None
        and config is None
        and base_dict.get("target") is None
    ):
        target = "ensemble"

    eff_candidates = mock_candidates if mock_candidates is not None else candidates
    overrides: dict[str, Any] = {
        "target": target,
        "backend": backend,
        "tier": tier,
        "where": where,
        "horizon": horizon,
        "max_evaluations": max_evaluations,
        "significance_alpha": significance_alpha,
        "worst_decile_floor": worst_decile_floor,
        "project_id": project_id,
        "location": location,
        "region": region,
        "model_name": model_name,
        "export_path": str(export_path) if export_path is not None else None,
        "random_seed": random_seed,
        "decision_metric": decision_metric,
        "timeout_seconds": timeout_seconds,
        "dry_run": dry_run,
        "mock_candidates": tuple(eff_candidates) if eff_candidates is not None else None,
        "lockdown_override_score": lockdown_override_score,
        "from_runs": tuple(from_runs) if from_runs is not None else None,
        "from_run_ids": tuple(str(r) for r in from_run_ids) if from_run_ids is not None else None,
        "dataset_id": dataset_id,
    }
    for k, v in overrides.items():
        if v is not None:
            base_dict[k] = v

    cfg = EvolveConfig.model_validate(base_dict)
    spec = get_target_seed(cfg.target)

    # Fast offline dry-run path (validates AST + temporal causality in <0.1s)
    if cfg.dry_run:
        ast_check = validate_candidate_ast(spec.seed_code)
        sample_df = pd.DataFrame(
            {
                "ts_id": ["s0"] * 16,
                "ds": pd.date_range("2025-01-01", periods=16, freq="D"),
                "y": [float(i + (i % 4)) for i in range(16)],
                "promo": [float(i % 2) for i in range(16)],
            }
        )
        causal_check = verify_no_future_leakage(synthesize_evolved_features, sample_df, horizon=4)
        dry_lb = pd.DataFrame(
            [
                {
                    "candidate_id": f"seed_{cfg.target}_dry_run",
                    "generation": 0,
                    "target": cfg.target,
                    "backend": cfg.backend,
                    "ast_valid": ast_check.valid,
                    "causal_valid": causal_check,
                    "inner_cv_score": 0.10,
                    "baseline_score": 0.10,
                    "inner_fva_pct": 0.0,
                    "dm_pvalue": 1.0,
                    "worst_decile_fva_pct": 0.0,
                    "gate1_passed": False,
                    "gate2_passed": False,
                    "lockdown_baseline_score": 0.10,
                    "lockdown_candidate_score": 0.10,
                    "gate3_passed": False,
                    "promoted": False,
                    "status": "dry_run",
                    "rejection_reason": "dry_run: offline pre-flight validation only",
                    "wall_seconds": round(time.monotonic() - t_start, 4),
                }
            ]
        )
        if cfg.export_path:
            out_p = Path(cfg.export_path)
            out_p.parent.mkdir(parents=True, exist_ok=True)
            out_p.write_text(spec.seed_code, encoding="utf-8")
        return EvolveResult(
            target=cfg.target,
            backend_used=cfg.backend,
            promoted=False,
            rejection_reason="dry_run: offline pre-flight validation only",
            baseline_score=0.10,
            inner_cv_score=0.10,
            lockdown_baseline_score=0.10,
            lockdown_candidate_score=0.10,
            fva_pct=0.0,
            dm_pvalue=1.0,
            worst_decile_fva_pct=0.0,
            champion_code=spec.seed_code,
            export_path=cfg.export_path,
            leaderboard_df=dry_lb,
            forecaster=None,
            assessment=None,
            evaluations_run=0,
            wall_seconds=time.monotonic() - t_start,
            candidate_code=spec.seed_code,
            diagnostics={
                "dry_run": True,
                "model_name": cfg.model_name,
                "ast_valid": ast_check.valid,
                "causal_valid": causal_check,
            },
            model_name=cfg.model_name,
        )

    # Pre-flight access probe for backend="alphaevolve" BEFORE running any backtests
    if cfg.backend == "alphaevolve" and alphaevolve_http_request is None:
        probe_alphaevolve_access(
            project_id=cfg.project_id,
            location=cfg.location,
            http_get=http_get,
        )

    is_post_run_call = (
        bool(cfg.from_runs)
        or bool(cfg.from_run_ids)
        or (data is not None and not isinstance(data, (pd.DataFrame, str)))
    )
    panel_df: Any = None if is_post_run_call else _resolve_input_dataframe(data)
    if data is not None and not isinstance(data, (pd.DataFrame, str)) and not cfg.from_runs:
        panel_df = data

    client = create_evolution_client(
        cfg.backend,
        target=cfg.target,
        project_id=cfg.project_id,
        location=cfg.location,
        region=cfg.region,
        model_name=cfg.model_name,
        max_evaluations=cfg.max_evaluations,
        mock_candidates=cfg.mock_candidates,
        genai_client=genai_client,
        alphaevolve_http_request=alphaevolve_http_request,
    )

    evaluator = EvolutionEvaluator(
        panel_df,
        from_runs=cfg.from_runs,
        from_run_ids=cfg.from_run_ids,
        dataset_id=cfg.dataset_id,
        project_id=cfg.project_id,
        region=cfg.region,
        target=cfg.target,
        backend=cfg.backend,
        tier=cfg.tier,
        where=cfg.where,
        horizon=cfg.horizon,
        significance_alpha=cfg.significance_alpha,
        worst_decile_floor=cfg.worst_decile_floor,
        timeout_seconds=cfg.timeout_seconds,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        freq=freq,
    )

    prof_dict = evaluator.profile_dict
    f_cfg = getattr(evaluator.forecaster, "config", None)
    f_feats = getattr(f_cfg, "features", None) if f_cfg is not None else None
    f_hier = getattr(f_cfg, "hierarchy", None) if f_cfg is not None else None
    mono_constraints: dict[str, Any] = (
        dict(getattr(f_feats, "monotonic_constraints", {}) or {}) if f_feats is not None else {}
    )
    if not mono_constraints and isinstance(prof_dict.get("monotonic_constraints"), Mapping):
        mono_constraints = dict(prof_dict["monotonic_constraints"])
    simplex_total = (
        prof_dict.get("simplex_total")
        if prof_dict.get("simplex_total") is not None
        else (getattr(f_feats, "simplex_sum", None) if f_feats is not None else None)
    )
    is_simplex = bool(prof_dict.get("is_compositional_simplex", False) or simplex_total is not None)
    hier_cols = list(
        prof_dict.get("hierarchy_id_cols")
        or (getattr(f_hier, "levels", []) if f_hier is not None else [])
    )
    rec_temporal = bool(
        prof_dict.get("reconcile_temporal", False)
        or (
            f_hier is not None
            and (
                bool(getattr(f_hier, "reconcile_temporal", False))
                or bool(getattr(f_hier, "cross_temporal", False))
            )
        )
    )
    f_cal = getattr(f_cfg, "calibration", None) if f_cfg is not None else None
    regime_shares_dict = dict(prof_dict.get("regime_shares") or {})
    cs_frac = float(
        prof_dict.get(
            "cold_start_fraction",
            regime_shares_dict.get("cold_start", 0.0),
        )
        or 0.0
    )
    has_cs = bool(
        prof_dict.get("has_cold_start", False)
        or cs_frac > 0.0
        or (getattr(f_feats, "cold_start_transfer", False) if f_feats is not None else False)
    )
    structural_diag: dict[str, Any] = {
        "monotonic_constraints": mono_constraints,
        "is_compositional_simplex": is_simplex,
        "simplex_total": simplex_total,
        "hierarchy_id_cols": hier_cols,
        "reconcile_temporal": rec_temporal,
        "has_cold_start": has_cs,
        "cold_start_fraction": cs_frac,
        "cold_start_donor_similarity": float(prof_dict.get("cold_start_donor_similarity", 0.0)),
        "calibration_method": str(
            prof_dict.get(
                "calibration_method",
                getattr(f_cal, "method", "conformal") if f_cal is not None else "conformal",
            )
        ),
        "residual_drift_ks_stat": float(prof_dict.get("residual_drift_ks_stat", 0.0)),
        "cross_series_residual_corr": float(
            prof_dict.get("cross_series_residual_corr", prof_dict.get("cross_series_corr", 0.0))
        ),
    }

    evaluations: list[CandidateEvaluation] = []
    current_parent_code = spec.seed_code
    last_diag: dict[str, Any] = {
        "fva_pct": 0.0,
        "dm_pvalue": 1.0,
        "worst_decile_fva": 0.0,
        "horizon_decay": "baseline",
        "baseline_score": evaluator.baseline_score,
        "inner_cv_score": evaluator.baseline_score,
        **structural_diag,
    }

    for gen in range(1, cfg.max_evaluations + 1):
        cand_code = client.propose_candidate(
            target=cfg.target,
            parent_code=current_parent_code,
            diagnostics=last_diag,
            generation=gen,
        )
        cand_eval = evaluator.evaluate_candidate_inner(cand_code, generation=gen)
        evaluations.append(cand_eval)

        cand_diag = {
            "fva_pct": cand_eval.inner_fva_pct,
            "dm_pvalue": cand_eval.dm_pvalue,
            "worst_decile_fva": cand_eval.worst_decile_fva_pct,
            "horizon_decay": "improved" if cand_eval.gate1_passed else "degraded",
            "baseline_score": cand_eval.baseline_score,
            "inner_cv_score": cand_eval.inner_cv_score,
            **structural_diag,
        }
        client.record_evaluation(
            program_id=cand_eval.candidate_id,
            code=cand_code,
            score=cand_eval.inner_cv_score,
            diagnostics=cand_diag,
        )
        if cand_eval.gate1_passed and math.isfinite(cand_eval.inner_cv_score):
            current_parent_code = cand_code
            last_diag = cand_diag

    # Select best inner-CV candidate (preferring candidates that passed both Gate 1 and Gate 2)
    gate12_winners = [e for e in evaluations if e.gate1_passed and e.gate2_passed]
    gate1_winners = [e for e in evaluations if e.gate1_passed]
    if gate12_winners:
        best_idx = min(
            range(len(evaluations)),
            key=lambda i: (
                evaluations[i].inner_cv_score
                if (evaluations[i].gate1_passed and evaluations[i].gate2_passed)
                else float("inf")
            ),
        )
    elif gate1_winners:
        best_idx = min(
            range(len(evaluations)),
            key=lambda i: (
                evaluations[i].inner_cv_score if evaluations[i].gate1_passed else float("inf")
            ),
        )
    else:
        best_idx = min(range(len(evaluations)), key=lambda i: evaluations[i].inner_cv_score)

    best_inner = evaluations[best_idx]
    final_eval = evaluator.evaluate_lockdown_gate3(best_inner)

    if cfg.lockdown_override_score is not None:
        forced_lock = float(cfg.lockdown_override_score)
        forced_g3 = bool(forced_lock < evaluator.lockdown_baseline_score - 1e-9)
        forced_promoted = bool(final_eval.gate1_passed and final_eval.gate2_passed and forced_g3)
        forced_reason = (
            None
            if forced_promoted
            else (
                f"Gate 3 (Held-Out Lockdown Fold): candidate improved inner CV "
                f"({final_eval.inner_cv_score:.4f} < {final_eval.baseline_score:.4f}) "
                f"but degraded on the unseen lockdown fold "
                f"({forced_lock:.4f} >= {evaluator.lockdown_baseline_score:.4f}). "
                f"Ratcheted back to Forecaster.auto() baseline."
            )
        )
        final_eval = CandidateEvaluation(
            **{
                **final_eval.__dict__,
                "lockdown_candidate_score": forced_lock,
                "gate3_passed": forced_g3,
                "promoted": forced_promoted,
                "status": "promoted_champion" if forced_promoted else "rejected_gate3",
                "rejection_reason": forced_reason,
            }
        )

    evaluations[best_idx] = final_eval
    leaderboard_df = pd.DataFrame([e.to_row() for e in evaluations])

    champion_code = final_eval.code if final_eval.promoted else spec.seed_code
    if cfg.export_path is not None:
        out_p = Path(cfg.export_path)
        out_p.parent.mkdir(parents=True, exist_ok=True)
        out_p.write_text(champion_code, encoding="utf-8")

    assessment_df = (
        evaluator.session.practitioner_assessment_df()
        if evaluator.session is not None
        else pd.DataFrame()
    )
    fva_pct = final_eval.inner_fva_pct
    if (
        final_eval.promoted
        and math.isfinite(final_eval.lockdown_baseline_score)
        and final_eval.lockdown_baseline_score > 1e-9
    ):
        lock_fva = (
            100.0
            * (final_eval.lockdown_baseline_score - final_eval.lockdown_candidate_score)
            / final_eval.lockdown_baseline_score
        )
        fva_pct = max(fva_pct, lock_fva)

    materialized_preds_df: pd.DataFrame | None = None
    if cfg.target == "ensemble":
        try:
            if final_eval.promoted:
                champ_fn = compile_candidate_symbol(champion_code, spec.entrypoint)
                champ_weights = champ_fn(evaluator.oof_df.copy(), evaluator.profile_dict)
                materialized_preds_df = evaluator.materialize_ensemble_predictions(
                    champ_weights, model_label="ensemble_evolved"
                )
            else:
                reigning = evaluator.reigning_champion_model or "ensemble_mean"
                materialized_preds_df = evaluator.materialize_ensemble_predictions(
                    {reigning: 1.0}, model_label=reigning
                )
        except Exception:  # noqa: BLE001 - best-effort forward prediction materialization
            materialized_preds_df = None

    merged_diagnostics: dict[str, Any] = {
        **evaluator.pool_diagnostics,
        "model_name": cfg.model_name,
        "reigning_champion_model": evaluator.reigning_champion_model,
        "gate1_passed": final_eval.gate1_passed,
        "gate2_passed": final_eval.gate2_passed,
        "gate3_passed": final_eval.gate3_passed,
        "status": final_eval.status,
    }

    return EvolveResult(
        target=cfg.target,
        backend_used=cfg.backend,
        promoted=final_eval.promoted,
        rejection_reason=final_eval.rejection_reason,
        baseline_score=evaluator.baseline_score,
        inner_cv_score=final_eval.inner_cv_score,
        lockdown_baseline_score=evaluator.lockdown_baseline_score,
        lockdown_candidate_score=final_eval.lockdown_candidate_score,
        fva_pct=round(float(fva_pct), 4),
        dm_pvalue=round(float(final_eval.dm_pvalue), 6)
        if math.isfinite(final_eval.dm_pvalue)
        else 1.0,
        worst_decile_fva_pct=round(float(final_eval.worst_decile_fva_pct), 4),
        champion_code=champion_code,
        export_path=cfg.export_path,
        leaderboard_df=leaderboard_df,
        forecaster=evaluator.forecaster,
        assessment=assessment_df,
        evaluations_run=len(evaluations),
        wall_seconds=time.monotonic() - t_start,
        candidate_code=final_eval.code,
        diagnostics=merged_diagnostics,
        predictions_df=materialized_preds_df,
        model_name=cfg.model_name,
    )