Skip to content

Auto-Forecaster & Closed-Loop autofocus

auto

Glass-Box Auto-Forecaster & Bounded autofocus Closed-Loop Controller.

Compiles a raw time-series DataFrame or BigQuery table into a fully validated, transparent :class:~scale_forecasting.config.RunConfig accompanied by a row-by-row :class:ConfigBlueprint rationale table, a parametric wall-clock and cloud cost estimate (:func:predict_run_duration), user scope & constraint pinning, and an optional closed-loop Plan -> Execute -> Observe -> Review -> Re-Plan (autofocus=True) controller supporting both multi-branch Tournament DAGs (autofocus_mode="dag") and linear refinement loops (autofocus_mode="linear").

Two Top-Level Dials + Optional User Constraint Pins

  1. Sandbox Envelope (where, allowed_families, goal, max_minutes, max_usd): Defines where compute is allowed to execute ("auto", "local", "bigquery", "cloud_cpu", "cloud_all"), which model families are eligible, the business optimization goal ("accuracy", "probabilistic", "service_level", "fast"), and hard wall-clock/cost limits.
  2. Observational Astronomy Exposure Tier (tier):
  3. "first_light" (~20s local / ~55s BQ / ~6m cloud): Rapid sanity check & FVA baseline (n_folds=1).
  4. "wide_field" (~2m local / ~2m BQ / ~7-16m cloud, Default): Balanced multi-family survey across Statistical, ML Trees, and Zero-Shot Foundation models (n_folds=2, max 2 passes).
  5. "deep_sky" (~6m local / ~4.5m BQ / ~12-22m cloud): Cross-series global + local + neural survey (tide, tsmixer, catboost, sarimax, autoets, n_folds=3, HPO, Tournament DAG).
  6. "deep_field" (~15m local / ~8m BQ / ~20-35m cloud): Exhaustive observatory exposure across all eligible families, HPO, and learned stacking (max 4 passes).
  7. Explicit User Scope & Constraint Pins (base_config, overrides, models, include_models, exclude_models, decision_metric, n_folds, hpo, ensemble, explainability): Users can pin any subset of the configuration while letting the Glass-Box compiler and autofocus optimize the remaining unpinned degrees of freedom.

Public surface: ConfigBlueprint, AutofocusPassRecord, NextLoopPreview, AutoForecastSession, inspect_panel_for_auto, build_config, auto_forecast.

AutoForecastSession dataclass

AutoForecastSession(
    blueprint,
    profile,
    tier,
    where,
    goal,
    max_minutes,
    max_usd,
    min_confidence,
    max_passes,
    autofocus_mode="dag",
    exclude_models=(),
    pinned_models=False,
    pinned_hpo=None,
    baselines=(),
    data_df=None,
    future_df=None,
    passes=list(),
    last_diagnostics_summary=dict(),
    leaderboard_df=DataFrame(),
    predictions_df=DataFrame(),
    oof_df=DataFrame(),
    fva_df=DataFrame(),
    horizon_decay_df=DataFrame(),
    bias_df=DataFrame(),
    attributions_df=DataFrame(),
    raw_predictions_df=DataFrame(),
    hierarchy_summary_df=DataFrame(),
    cell_cache=dict(),
    champion_pass_id="1",
    champion_score=float("inf"),
    champion_outputs=dict(),
)

State container attached to a Forecaster produced by Forecaster.auto().

best_metric property

best_metric

Return the winning decision metric value from the session champion pass.

best_model property

best_model

Return the winning model from the session champion pass.

decision_metric property

decision_metric

Return the decision metric name from the session.

run_id property

run_id

Return the winning session champion run_id (or blueprint run_id).

assess

assess()

Return a 7-Question Practitioner Assessment DataFrame with full text report representation.

Source code in src/scale_forecasting/auto.py
def assess(self) -> pd.DataFrame:
    """Return a 7-Question Practitioner Assessment DataFrame with full text report
    representation.
    """
    prof_str = self.profile.explain()
    assess_df = self.practitioner_assessment_df()
    champ = self.champion_record()
    head = (
        f"Practitioner Trust & Evidence Assessment : {self.run_id} | "
        f"Champion='{champ.champion_model if champ else 'n/a'}' "
        f"({self.decision_metric}={champ.champion_score if champ else float('nan'):.4f})"
    )
    report_text = f"{prof_str}\n\n{head}\n\n{assess_df.to_string(index=False)}"
    frame = PractitionerAssessmentFrame(assess_df)
    frame._report_text = report_text
    return frame

baseline_value_df

baseline_value_df()

Compare the session champion against the 4-anchor baseline ladder and challengers.

When a plain univariate model (or univariate foundation model) wins as the session champion, this table also highlights every complex/multivariate/global challenger and exogenous covariate that the univariate champion outperformed (baseline_role = 'beaten_complex_challenger').

Source code in src/scale_forecasting/auto.py
def baseline_value_df(self) -> pd.DataFrame:
    """Compare the session champion against the 4-anchor baseline ladder and challengers.

    When a plain univariate model (or univariate foundation model) wins as the session
    champion, this table also highlights every complex/multivariate/global challenger and
    exogenous covariate that the univariate champion outperformed (`baseline_role =
    'beaten_complex_challenger'`).
    """
    cols = [
        "baseline_role",
        "baseline_model",
        "champion_model",
        "decision_metric",
        "baseline_score",
        "champion_score",
        "fva_vs_baseline_pct",
        "dm_pvalue",
        "series_win_rate_pct",
        "champion_is_univariate",
        "beaten_challengers",
        "univariate_edge_pct",
        "verdict",
    ]
    champ = self.champion_record()
    if champ is None:
        return pd.DataFrame(columns=cols)

    decision = self.decision_metric
    metric_col = (
        f"mean_{decision}" if f"mean_{decision}" in self.leaderboard_df.columns else decision
    )
    champ_model = champ.champion_model
    champ_score = champ.champion_score
    champ_is_uni = champ.champion_is_univariate
    beaten_str = ", ".join(champ.beaten_challengers) if champ.beaten_challengers else "(none)"

    # Gather scores across all passes so baselines/challengers from Pass 1 are always visible
    scores_by_model: dict[str, float] = {}
    for p_out in (
        self.champion_outputs,
        {"leaderboard_df": self.leaderboard_df, "fva_df": self.fva_df},
    ):
        lb = p_out.get("leaderboard_df", pd.DataFrame())
        if isinstance(lb, pd.DataFrame) and not lb.empty:
            m_col = "model_type" if "model_type" in lb.columns else "model"
            s_col = metric_col if metric_col in lb.columns else lb.columns[-1]
            for _, r_lb in lb.iterrows():
                m_name = str(r_lb[m_col])
                val = float(pd.to_numeric(r_lb[s_col], errors="coerce"))
                if math.isfinite(val) and (
                    m_name not in scores_by_model or val < scores_by_model[m_name]
                ):
                    scores_by_model[m_name] = val

    # Inspect cell_cache across passes so every model from Pass 1 or branches is scored
    if self.cell_cache:
        by_m_vals: dict[str, list[float]] = {}
        for c_res in self.cell_cache.values():
            if c_res.status == "ok" and decision in c_res.metrics:
                v_m = float(c_res.metrics[decision])
                if math.isfinite(v_m):
                    by_m_vals.setdefault(c_res.model_type, []).append(v_m)
        for m_k, vals_k in by_m_vals.items():
            if vals_k:
                mean_v = float(np.mean(vals_k))
                if m_k not in scores_by_model:
                    scores_by_model[m_k] = mean_v

    active_baselines = list(self.baselines or self.blueprint.baselines)
    if not active_baselines:
        active_baselines = [
            {"baseline_role": "naive_anchor", "model_type": "naive_seasonal"},
            {"baseline_role": "plain_univariate_stat", "model_type": "theta"},
        ]

    # Compute univariate edge % when champion is univariate and beat complex challengers
    complex_scores: list[float] = []
    for ch_name in champ.beaten_challengers:
        ch_model = ch_name.split(" (", 1)[0]
        if ch_model in scores_by_model and scores_by_model[ch_model] > champ_score:
            complex_scores.append(scores_by_model[ch_model])
    uni_edge_pct = (
        round(
            100.0 * (min(complex_scores) - champ_score) / max(1e-9, min(complex_scores)),
            2,
        )
        if (champ_is_uni and complex_scores and math.isfinite(champ_score))
        else 0.0
    )

    # Lookup per-series errors from OOF to compute series_win_rate_pct and DM p-value
    series_err_by_model: dict[str, dict[str, float]] = {}
    if not self.oof_df.empty and {"ts_id", "model_type", "y_true", "yhat"}.issubset(
        self.oof_df.columns
    ):
        oof_work = self.oof_df.copy()
        oof_work["abs_err"] = np.abs(
            pd.to_numeric(oof_work["y_true"], errors="coerce")
            - pd.to_numeric(oof_work["yhat"], errors="coerce")
        )
        for (m_t, tid), grp in oof_work.groupby(["model_type", "ts_id"], sort=False):
            series_err_by_model.setdefault(str(m_t), {})[str(tid)] = float(
                grp["abs_err"].mean()
            )

    def _win_rate_vs(base_m: str) -> float:
        c_map = series_err_by_model.get(champ_model, {})
        b_map = series_err_by_model.get(base_m, {})
        shared = [k for k in c_map if k in b_map]
        if not shared:
            return 100.0 if scores_by_model.get(base_m, champ_score) > champ_score else 50.0
        wins = sum(1 for k in shared if c_map[k] <= b_map[k] + 1e-9)
        return round(100.0 * wins / len(shared), 1)

    rows: list[dict[str, Any]] = []
    seen_roles_models: set[tuple[str, str]] = set()
    for b_entry in active_baselines:
        role = str(b_entry.get("baseline_role", "baseline"))
        b_model = str(b_entry.get("model_type", "naive_seasonal"))
        # Resolve fallback if exact variant didn't run
        resolved_b = b_model
        if resolved_b not in scores_by_model:
            base_b = b_model.split("@", 1)[0]
            cand_matches = [
                k for k in scores_by_model if k == base_b or k.startswith(f"{base_b}@")
            ]
            if cand_matches:
                resolved_b = cand_matches[0]
        if resolved_b not in scores_by_model:
            continue
        if (role, resolved_b) in seen_roles_models:
            continue
        seen_roles_models.add((role, resolved_b))
        b_score = scores_by_model[resolved_b]
        fva_gain = (
            round(100.0 * (b_score - champ_score) / max(1e-9, b_score), 2)
            if math.isfinite(b_score) and math.isfinite(champ_score) and b_score > 1e-9
            else 0.0
        )
        win_rate = _win_rate_vs(resolved_b)
        dm_p = champ.dm_pvalue if role == "naive_anchor" else None
        if resolved_b == champ_model:
            verdict = (
                f"champion_is_{role} (beat {beaten_str} by +{uni_edge_pct:.2f}%)"
                if (champ_is_uni and champ.beaten_challengers)
                else f"champion_is_{role}"
            )
        elif fva_gain > 0.25:
            verdict = f"beats_{role} (+{fva_gain:.2f}%)"
        elif fva_gain >= -0.25:
            verdict = f"ties_{role} ({fva_gain:+.2f}%)"
        else:
            verdict = f"trails_{role} ({fva_gain:+.2f}%)"

        rows.append(
            {
                "baseline_role": role,
                "baseline_model": resolved_b,
                "champion_model": champ_model,
                "decision_metric": decision,
                "baseline_score": round(b_score, 4),
                "champion_score": round(champ_score, 4),
                "fva_vs_baseline_pct": fva_gain,
                "dm_pvalue": round(dm_p, 4) if dm_p is not None else None,
                "series_win_rate_pct": win_rate,
                "champion_is_univariate": champ_is_uni,
                "beaten_challengers": beaten_str,
                "univariate_edge_pct": uni_edge_pct,
                "verdict": verdict,
            }
        )

    # When a plain univariate (or univariate foundation) model wins as session champion,
    # append explicit rows showing each complex/multivariate/global challenger it beat!
    if champ_is_uni and champ.beaten_challengers:
        for ch_label in champ.beaten_challengers:
            ch_m = ch_label.split(" (", 1)[0]
            if (
                ch_m in scores_by_model
                and ("beaten_complex_challenger", ch_m) not in seen_roles_models
            ):
                seen_roles_models.add(("beaten_complex_challenger", ch_m))
                ch_score = scores_by_model[ch_m]
                edge_vs_ch = (
                    round(100.0 * (ch_score - champ_score) / max(1e-9, ch_score), 2)
                    if math.isfinite(ch_score) and ch_score > 1e-9
                    else 0.0
                )
                rows.append(
                    {
                        "baseline_role": "beaten_complex_challenger",
                        "baseline_model": ch_label,
                        "champion_model": champ_model,
                        "decision_metric": decision,
                        "baseline_score": round(ch_score, 4),
                        "champion_score": round(champ_score, 4),
                        "fva_vs_baseline_pct": edge_vs_ch,
                        "dm_pvalue": None,
                        "series_win_rate_pct": _win_rate_vs(ch_m),
                        "champion_is_univariate": True,
                        "beaten_challengers": beaten_str,
                        "univariate_edge_pct": edge_vs_ch,
                        "verdict": f"univariate_champion_beat_{ch_m} (+{edge_vs_ch:.2f}%)",
                    }
                )

    return pd.DataFrame(rows, columns=cols)

champion_record

champion_record()

Return the :class:AutofocusPassRecord marked is_session_champion=True.

Source code in src/scale_forecasting/auto.py
def champion_record(self) -> AutofocusPassRecord | None:
    """Return the :class:`AutofocusPassRecord` marked ``is_session_champion=True``."""
    for p in self.passes:
        if p.is_session_champion:
            return p
    return self.passes[-1] if self.passes else None

compare_models

compare_models(model_a=None, model_b=None)

Head-to-head comparison answering 'Is Model A better than Model B?'.

When model_a is None, defaults to the Session Champion (self.best_model). When model_b is None, compares model_a against every other model evaluated across the session, reporting score delta, FVA lift %, series-by-series win rate %, and Diebold–Mariano $p$-value.

Source code in src/scale_forecasting/auto.py
def compare_models(
    self,
    model_a: str | None = None,
    model_b: str | None = None,
) -> pd.DataFrame:
    """Head-to-head comparison answering *'Is Model A better than Model B?'*.

    When ``model_a`` is ``None``, defaults to the Session Champion (`self.best_model`). When
    ``model_b`` is ``None``, compares ``model_a`` against every other model evaluated across
    the session, reporting score delta, FVA lift %, series-by-series win rate %, and
    Diebold–Mariano $p$-value.
    """
    from .diagnostics import compute_fva

    cols = [
        "model_a",
        "model_b",
        "decision_metric",
        "score_a",
        "score_b",
        "lift_pct",
        "series_win_rate_pct",
        "dm_pvalue",
        "significant_at_10pct",
        "verdict",
    ]
    champ = self.champion_record()
    if champ is None:
        return pd.DataFrame(columns=cols)

    decision = self.decision_metric
    metric_col = (
        f"mean_{decision}" if f"mean_{decision}" in self.leaderboard_df.columns else decision
    )
    scores_by_model: dict[str, float] = {}
    if not self.leaderboard_df.empty:
        m_col = "model_type" if "model_type" in self.leaderboard_df.columns else "model"
        s_col = (
            metric_col
            if metric_col in self.leaderboard_df.columns
            else self.leaderboard_df.columns[-1]
        )
        for _, r_lb in self.leaderboard_df.iterrows():
            m_name = str(r_lb[m_col])
            val = float(pd.to_numeric(r_lb[s_col], errors="coerce"))
            if math.isfinite(val):
                scores_by_model[m_name] = val
    if self.cell_cache:
        by_m_vals: dict[str, list[float]] = {}
        for c_res in self.cell_cache.values():
            if c_res.status == "ok" and decision in c_res.metrics:
                v_m = float(c_res.metrics[decision])
                if math.isfinite(v_m):
                    by_m_vals.setdefault(c_res.model_type, []).append(v_m)
        for m_k, vals_k in by_m_vals.items():
            if vals_k and m_k not in scores_by_model:
                scores_by_model[m_k] = float(np.mean(vals_k))

    target_a = model_a or champ.champion_model
    if target_a not in scores_by_model:
        scores_by_model[target_a] = champ.champion_score
    score_a = scores_by_model[target_a]

    candidates_b = (
        [model_b]
        if model_b is not None
        else [
            m for m, _ in sorted(scores_by_model.items(), key=lambda kv: kv[1]) if m != target_a
        ]
    )

    series_err_by_model: dict[str, dict[str, float]] = {}
    if not self.oof_df.empty and {"ts_id", "model_type", "y_true", "yhat"}.issubset(
        self.oof_df.columns
    ):
        oof_w = self.oof_df.copy()
        oof_w["abs_err"] = np.abs(
            pd.to_numeric(oof_w["y_true"], errors="coerce")
            - pd.to_numeric(oof_w["yhat"], errors="coerce")
        )
        for (m_t, tid), grp in oof_w.groupby(["model_type", "ts_id"], sort=False):
            series_err_by_model.setdefault(str(m_t), {})[str(tid)] = float(
                grp["abs_err"].mean()
            )

    rows: list[dict[str, Any]] = []
    for b_name in candidates_b:
        if b_name is None or b_name not in scores_by_model:
            continue
        score_b = scores_by_model[b_name]
        lift_pct = (
            round(100.0 * (score_b - score_a) / max(1e-9, score_b), 2)
            if math.isfinite(score_a) and math.isfinite(score_b) and score_b > 1e-9
            else 0.0
        )
        a_map = series_err_by_model.get(target_a, {})
        b_map = series_err_by_model.get(b_name, {})
        shared = [k for k in a_map if k in b_map]
        win_rate = (
            round(
                100.0 * sum(1 for k in shared if a_map[k] <= b_map[k] + 1e-9) / len(shared),
                1,
            )
            if shared
            else (100.0 if score_a < score_b else 0.0)
        )
        dm_p: float | None = None
        if not self.oof_df.empty:
            with contextlib.suppress(Exception):
                fva_sub = compute_fva(self.oof_df, baseline=b_name, metric=decision)
                if not fva_sub.empty and "model_type" in fva_sub.columns:
                    m_row = fva_sub[fva_sub["model_type"] == target_a]
                    if not m_row.empty and "dm_pvalue" in m_row.columns:
                        p_val = float(
                            pd.to_numeric(m_row["dm_pvalue"].iloc[0], errors="coerce")
                        )
                        if math.isfinite(p_val):
                            dm_p = round(p_val, 4)
        sig = bool(dm_p is not None and dm_p <= 0.10 and abs(lift_pct) >= 0.5)
        if lift_pct > 0.5:
            verdict = (
                f"{target_a} beats {b_name} by +{lift_pct:.2f}% "
                f"({'statistically significant' if sig else 'directional lift'}, "
                f"wins {win_rate:.0f}% of series)"
            )
        elif lift_pct >= -0.5:
            verdict = f"Statistical tie ({lift_pct:+.2f}%, wins {win_rate:.0f}% of series)"
        else:
            verdict = f"{target_a} trails {b_name} by {lift_pct:+.2f}%"
        rows.append(
            {
                "model_a": target_a,
                "model_b": b_name,
                "decision_metric": decision,
                "score_a": round(score_a, 4),
                "score_b": round(score_b, 4),
                "lift_pct": lift_pct,
                "series_win_rate_pct": win_rate,
                "dm_pvalue": dm_p,
                "significant_at_10pct": sig,
                "verdict": verdict,
            }
        )
    return pd.DataFrame(rows, columns=cols)

diff_df

diff_df()

Return a parameter-by-parameter and score diff table across all autofocus passes.

Source code in src/scale_forecasting/auto.py
def diff_df(self) -> pd.DataFrame:
    """Return a parameter-by-parameter and score diff table across all `autofocus` passes."""
    cols = [
        "pass_index",
        "pass_id",
        "parent_pass_ids",
        "branch_hypothesis",
        "action",
        "parameter",
        "old_value",
        "new_value",
        "champion_model",
        "champion_score",
        "delta_vs_pass1_pct",
        "is_session_champion",
        "evidence",
        "rationale",
    ]
    if not self.passes:
        return pd.DataFrame(columns=cols)
    p1_score = self.passes[0].champion_score
    rows: list[dict[str, Any]] = []
    for p in self.passes:
        delta_pct = (
            round(100.0 * (p1_score - p.champion_score) / max(1e-9, p1_score), 2)
            if math.isfinite(p1_score) and math.isfinite(p.champion_score) and p1_score > 1e-9
            else 0.0
        )
        if not p.mutations_detail:
            rows.append(
                {
                    "pass_index": p.pass_index,
                    "pass_id": p.pass_id,
                    "parent_pass_ids": ", ".join(p.parent_pass_ids) or "root",
                    "branch_hypothesis": p.branch_hypothesis,
                    "action": "initial_tier_compilation",
                    "parameter": "models",
                    "old_value": "(none)",
                    "new_value": ", ".join(p.config.models),
                    "champion_model": p.champion_model,
                    "champion_score": round(p.champion_score, 4),
                    "delta_vs_pass1_pct": delta_pct,
                    "is_session_champion": p.is_session_champion,
                    "evidence": f"tier='{p.tier}'",
                    "rationale": "Initial Glass-Box exposure tier model & feature compilation.",
                }
            )
        else:
            for m in p.mutations_detail:
                rows.append(
                    {
                        "pass_index": p.pass_index,
                        "pass_id": p.pass_id,
                        "parent_pass_ids": ", ".join(p.parent_pass_ids) or "1",
                        "branch_hypothesis": p.branch_hypothesis,
                        "action": m.get("action", ""),
                        "parameter": m.get("parameter", ""),
                        "old_value": m.get("old_value", ""),
                        "new_value": m.get("new_value", ""),
                        "champion_model": p.champion_model,
                        "champion_score": round(p.champion_score, 4),
                        "delta_vs_pass1_pct": delta_pct,
                        "is_session_champion": p.is_session_champion,
                        "evidence": m.get("evidence", ""),
                        "rationale": m.get("rationale", ""),
                    }
                )
    return pd.DataFrame(rows, columns=cols)

explain_decisions_df

explain_decisions_df()

Return a unified audit table of Pass 1 blueprint decisions + autofocus mutations.

Source code in src/scale_forecasting/auto.py
def explain_decisions_df(self) -> pd.DataFrame:
    """Return a unified audit table of Pass 1 blueprint decisions + `autofocus` mutations."""
    cols = [
        "phase",
        "source",
        "category",
        "parameter",
        "value",
        "evidence",
        "rationale",
        "realized_delta_pct",
        "is_session_champion",
    ]
    rows: list[dict[str, Any]] = []
    p1_score = self.passes[0].champion_score if self.passes else float("nan")
    p1_champ = self.passes[0].is_session_champion if self.passes else True
    for _, r in self.blueprint.rationale_df.iterrows():
        cat = str(r.get("category", ""))
        src = (
            "user_pin"
            if cat == "user_constraint" or "[PINNED]" in str(r.get("evidence", ""))
            else "auto_policy"
        )
        rows.append(
            {
                "phase": "pass_1_blueprint",
                "source": src,
                "category": cat,
                "parameter": str(r.get("parameter", "")),
                "value": str(r.get("value", "")),
                "evidence": str(r.get("evidence", "")),
                "rationale": str(r.get("rationale", "")),
                "realized_delta_pct": 0.0,
                "is_session_champion": p1_champ,
            }
        )
    for p in self.passes[1:]:
        delta_pct = (
            round(100.0 * (p1_score - p.champion_score) / max(1e-9, p1_score), 2)
            if math.isfinite(p1_score) and math.isfinite(p.champion_score) and p1_score > 1e-9
            else 0.0
        )
        for m in p.mutations_detail:
            rows.append(
                {
                    "phase": f"pass_{p.pass_id}_autofocus",
                    "source": "autofocus_dag" if len(p.pass_id) > 1 else "autofocus_loop",
                    "category": m.get("action", "autofocus"),
                    "parameter": m.get("parameter", ""),
                    "value": m.get("new_value", ""),
                    "evidence": m.get("evidence", ""),
                    "rationale": m.get("rationale", ""),
                    "realized_delta_pct": delta_pct,
                    "is_session_champion": p.is_session_champion,
                }
            )
    champ = self.champion_record()
    if champ is not None and champ.champion_is_univariate and champ.beaten_challengers:
        rows.append(
            {
                "phase": f"pass_{champ.pass_id}_champion_verdict",
                "source": "champion_ratchet",
                "category": "univariate_champion_victory",
                "parameter": "champion_model",
                "value": champ.champion_model,
                "evidence": f"beaten_challengers={list(champ.beaten_challengers)}",
                "rationale": (
                    f"Plain univariate model '{champ.champion_model}' won the session "
                    f"championship ({champ.decision_metric}={champ.champion_score:.4f}), "
                    f"outperforming complex/multivariate challengers "
                    f"({', '.join(champ.beaten_challengers)})."
                ),
                "realized_delta_pct": round(champ.fva_vs_naive_pct, 2),
                "is_session_champion": True,
            }
        )
    return pd.DataFrame(rows, columns=cols)

hierarchy_value_df

hierarchy_value_df()

Return per-level accuracy and reconciliation lift across the hierarchy tree.

Source code in src/scale_forecasting/auto.py
def hierarchy_value_df(self) -> pd.DataFrame:
    """Return per-level accuracy and reconciliation lift across the hierarchy tree."""
    if not self.hierarchy_summary_df.empty:
        return self.hierarchy_summary_df.copy()
    return pd.DataFrame(
        columns=[
            "hierarchy_level",
            "n_nodes",
            "reconciliation_method",
            "decision_metric",
            "unreconciled_score",
            "reconciled_score",
            "reconciliation_lift_pct",
            "max_coherence_residual",
            "negative_leaf_count",
        ]
    )

ledger_df

ledger_df()

Return a tidy DataFrame of all executed autofocus passes and DAG branches.

Source code in src/scale_forecasting/auto.py
def ledger_df(self) -> pd.DataFrame:
    """Return a tidy DataFrame of all executed `autofocus` passes and DAG branches."""
    rows = [
        {
            "pass_index": p.pass_index,
            "pass_id": p.pass_id,
            "parent_pass_ids": ", ".join(p.parent_pass_ids) if p.parent_pass_ids else "root",
            "branch_hypothesis": p.branch_hypothesis,
            "run_id": p.run_id,
            "tier": p.tier,
            "models_total": p.models_total,
            "models_borrowed": p.models_borrowed,
            "models_executed": p.models_executed,
            "champion_model": p.champion_model,
            "decision_metric": p.decision_metric,
            "champion_score": round(p.champion_score, 4),
            "fva_vs_naive_pct": round(p.fva_vs_naive_pct, 2),
            "fva_vs_univariate_pct": round(p.fva_vs_univariate_pct, 2),
            "fva_vs_foundation_pct": round(p.fva_vs_foundation_pct, 2),
            "covariate_lift_pct": round(p.covariate_lift_pct, 2),
            "reconciliation_lift_pct": round(p.reconciliation_lift_pct, 2),
            "champion_is_univariate": p.champion_is_univariate,
            "beaten_challengers": ", ".join(p.beaten_challengers)
            if p.beaten_challengers
            else "(none)",
            "dm_pvalue": round(p.dm_pvalue, 4) if p.dm_pvalue is not None else None,
            "predicted_p50_s": round(p.predicted_p50_s, 2),
            "actual_wall_s": round(p.actual_wall_s, 2),
            "continue_confidence": round(p.continue_confidence, 3),
            "expected_next_gain_pct": round(p.expected_next_gain_pct, 2),
            "mutations_applied": ", ".join(p.mutations_applied)
            if p.mutations_applied
            else "initial_pass",
            "is_session_champion": p.is_session_champion,
            "stop_or_continue_reason": p.stop_or_continue_reason,
        }
        for p in self.passes
    ]
    return pd.DataFrame(rows)

plot_promo_elasticity

plot_promo_elasticity(
    *,
    data=None,
    ts_id=None,
    promo_col=None,
    price_col=None,
    ax=None,
    title=None,
)

Plot organic baseline vs. promotional lift and post-promo dip for ts_id.

Source code in src/scale_forecasting/auto.py
def plot_promo_elasticity(
    self,
    *,
    data: pd.DataFrame | None = None,
    ts_id: str | None = None,
    promo_col: str | None = None,
    price_col: str | None = None,
    ax: Any = None,
    title: str | None = None,
) -> Any:
    """Plot organic baseline vs. promotional lift and post-promo dip for ``ts_id``."""
    from .elasticity import plot_promo_elasticity

    decomp = self.promo_elasticity_df(
        data=data, promo_col=promo_col, price_col=price_col, summary=False
    )
    return plot_promo_elasticity(decomp, ts_id=ts_id, ax=ax, title=title)

practitioner_assessment_df

practitioner_assessment_df()

Return a 7-row Practitioner Trust & Evidence DataFrame answering the 7 core questions forecasters ask about any run.

Source code in src/scale_forecasting/auto.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
def practitioner_assessment_df(self) -> pd.DataFrame:
    """Return a 7-row Practitioner Trust & Evidence ``DataFrame`` answering the 7 core
    questions forecasters ask about any run.
    """
    cols = [
        "question_id",
        "question",
        "verdict",
        "answer",
        "evidence",
        "recommendation",
    ]
    champ = self.champion_record()
    if champ is None:
        return pd.DataFrame(columns=cols)

    decision = self.decision_metric
    bval_df = self.baseline_value_df()
    hval_df = self.hierarchy_value_df()
    diag = dict(self.last_diagnostics_summary)

    # 1. Is this model better than simple baselines / Model X?
    fva_naive = champ.fva_vs_naive_pct
    fva_uni = champ.fva_vs_univariate_pct
    dm_p = champ.dm_pvalue
    if champ.champion_is_univariate and champ.beaten_challengers:
        q1_verdict = "univariate_champion_wins"
        beaten_str = ", ".join(champ.beaten_challengers)
        q1_ans = (
            f"Plain univariate model '{champ.champion_model}' beat both seasonal naive "
            f"(+{fva_naive:.2f}%) and complex challengers ({beaten_str})."
        )
    elif fva_naive > 1.0:
        q1_verdict = "verified_lift"
        q1_ans = (
            f"Champion '{champ.champion_model}' reduced {decision} by +{fva_naive:.2f}% vs. "
            f"seasonal naive and +{fva_uni:.2f}% vs. plain univariate baseline."
        )
    else:
        q1_verdict = "near_baseline"
        q1_ans = (
            f"Champion '{champ.champion_model}' is within {fva_naive:+.2f}% of baseline; "
            "series behaves close to a simple seasonal/random-walk floor."
        )
    q1_ev = (
        f"champion={champ.champion_model} ({decision}={champ.champion_score:.4f}), "
        f"fva_naive={fva_naive:+.2f}%, dm_pvalue={dm_p if dm_p is not None else 'n/a'}"
    )

    # 2. Do ensembles help?
    is_ens_champ = champ.champion_model.startswith("ensemble_")
    base_rows = (
        self.leaderboard_df[
            ~self.leaderboard_df["model_type"].astype(str).str.startswith("ensemble_")
        ]
        if not self.leaderboard_df.empty and "model_type" in self.leaderboard_df.columns
        else pd.DataFrame()
    )
    ens_rows = (
        self.leaderboard_df[
            self.leaderboard_df["model_type"].astype(str).str.startswith("ensemble_")
        ]
        if not self.leaderboard_df.empty and "model_type" in self.leaderboard_df.columns
        else pd.DataFrame()
    )
    m_col = (
        f"mean_{decision}" if f"mean_{decision}" in self.leaderboard_df.columns else decision
    )
    best_base_name = (
        str(base_rows["model_type"].iloc[0]) if not base_rows.empty else champ.champion_model
    )
    best_base_sc = (
        float(pd.to_numeric(base_rows[m_col].iloc[0], errors="coerce"))
        if not base_rows.empty and m_col in base_rows.columns
        else champ.champion_score
    )
    best_ens_name = str(ens_rows["model_type"].iloc[0]) if not ens_rows.empty else "(none)"
    best_ens_sc = (
        float(pd.to_numeric(ens_rows[m_col].iloc[0], errors="coerce"))
        if not ens_rows.empty and m_col in ens_rows.columns
        else float("nan")
    )
    ens_lift = (
        round(100.0 * (best_base_sc - best_ens_sc) / max(1e-9, best_base_sc), 2)
        if math.isfinite(best_base_sc) and math.isfinite(best_ens_sc) and best_base_sc > 1e-9
        else 0.0
    )
    if is_ens_champ and ens_lift > 0.0:
        q2_verdict = "ensemble_helps"
        q2_ans = (
            f"Yes — '{best_ens_name}' outperformed the best single model ('{best_base_name}') "
            f"by +{ens_lift:.2f}%."
        )
    elif math.isfinite(best_ens_sc):
        q2_verdict = "single_model_preferred"
        q2_ans = (
            f"Single model '{best_base_name}' matched or beat '{best_ens_name}' "
            f"(ensemble delta={ens_lift:+.2f}%); parsimony rule keeps the simpler model."
        )
    else:
        q2_verdict = "single_model_only"
        q2_ans = f"Single model '{best_base_name}' selected (no multi-model ensemble needed)."
    q2_ev = f"best_single={best_base_name} ({best_base_sc:.4f}), best_ensemble={best_ens_name}"

    # 3. Do covariates help or is it overfitting?
    all_covs = (
        list(self.profile.future_covariates)
        + list(self.profile.past_covariates)
        + list(self.profile.static_covariates)
    )
    kept_covs = list(champ.config.features.future_covariates) + list(
        champ.config.features.past_covariates
    )
    pruned_covs = [c for c in all_covs if c not in kept_covs]
    mono_constraints = dict(champ.config.features.monotonic_constraints or {})
    monotone_models = [m for m in champ.config.models if "@monotone" in m]
    hw_cfg = champ.config.features.holiday_window
    hw_active = bool(hw_cfg is not None and getattr(hw_cfg, "enabled", False))
    guardrail_notes: list[str] = []
    guardrail_ev: list[str] = []
    if mono_constraints or monotone_models:
        guardrail_notes.append(
            f"structural sign guardrails enforced (monotonic_constraints={mono_constraints}"
            + (f", monotone_models={monotone_models}" if monotone_models else "")
            + ")"
        )
        guardrail_ev.append(f"monotonic_constraints={mono_constraints}")
        if monotone_models:
            guardrail_ev.append(f"monotone_models={monotone_models}")
    if hw_active and hw_cfg is not None:
        guardrail_notes.append(
            f"asymmetric holiday window active (-{hw_cfg.pre_holiday_days}d/+"
            f"{hw_cfg.post_holiday_days}d, kernel='{hw_cfg.kernel}')"
        )
        guardrail_ev.append(
            f"holiday_window=(-{hw_cfg.pre_holiday_days}, +{hw_cfg.post_holiday_days}, "
            f"'{hw_cfg.kernel}')"
        )
    guardrail_suffix = f" ({'; '.join(guardrail_notes)})" if guardrail_notes else ""
    guardrail_ev_suffix = f", {', '.join(guardrail_ev)}" if guardrail_ev else ""

    if not all_covs:
        q3_verdict = "univariate_panel"
        q3_ans = (
            "No external covariates in source data; forecast relies on target history "
            f"and calendar cycles{guardrail_suffix}."
        )
        q3_ev = f"covariates=0{guardrail_ev_suffix}"
    elif not kept_covs or champ.champion_is_univariate:
        q3_verdict = "overfitting_prevented"
        pruned_list = pruned_covs or all_covs
        q3_ans = (
            f"Covariates did not improve out-of-fold accuracy (pruned={pruned_list}); "
            f"univariate model won, preventing covariate overfitting{guardrail_suffix}."
        )
        q3_ev = f"initial_covs={all_covs}, kept_covs={kept_covs}{guardrail_ev_suffix}"
    elif pruned_covs:
        q3_verdict = "selective_signal_kept"
        q3_ans = (
            f"True drivers {kept_covs} improved accuracy (+{fva_uni:.2f}% vs. univariate), "
            f"while noisy decoy columns {pruned_covs} were automatically pruned"
            f"{guardrail_suffix}."
        )
        q3_ev = (
            f"kept={kept_covs}, pruned_decoys={pruned_covs}, "
            f"fva_vs_univariate=+{fva_uni:.2f}%{guardrail_ev_suffix}"
        )
    else:
        q3_verdict = "covariates_help"
        q3_ans = (
            f"Covariates {kept_covs} added +{fva_uni:.2f}% lift over plain "
            f"univariate baselines{guardrail_suffix}."
        )
        q3_ev = (
            f"active_covariates={kept_covs}, fva_vs_univariate=+{fva_uni:.2f}%"
            f"{guardrail_ev_suffix}"
        )

    # 4. Does global provide an advantage over local?
    global_models = [
        m for m in champ.config.models if "@global" in m or "@similarity_global" in m
    ]
    sim_global_models = [m for m in champ.config.models if "@similarity_global" in m]
    opt_k = int(getattr(self.profile, "optimal_similarity_clusters", 1))
    sim_sil = float(getattr(self.profile, "similarity_silhouette_score", 0.0))
    mean_sim = float(getattr(self.profile, "mean_pairwise_similarity", 0.0))
    donor_sim = float(
        diag.get(
            "cold_start_donor_similarity",
            getattr(self.profile, "cold_start_donor_similarity", 0.0),
        )
    )
    cs_transfer_on = bool(
        getattr(champ.config.features, "cold_start_transfer", False) or donor_sim >= 0.65
    )
    donor_note = (
        f" Cold-start analog donor shrinkage active (donor_similarity={donor_sim:.2f})."
        if cs_transfer_on
        else ""
    )
    sim_note = (
        f" Trajectory similarity clustering identified K={opt_k} peer clusters "
        f"(silhouette={sim_sil:.2f}, mean_similarity={mean_sim:.2f}"
        + (f", similarity_global={sim_global_models}" if sim_global_models else "")
        + ")."
    )
    if global_models:
        q4_verdict = "global_active"
        q4_ans = (
            f"Cross-series @global/@similarity_global models ({', '.join(global_models)}) are "
            f"active for scale_regime='{self.profile.scale_regime}' "
            f"(n_series={self.profile.n_series}, corr={self.profile.cross_series_corr:.2f})."
            f"{sim_note}{donor_note}"
        )
    else:
        q4_verdict = "local_per_series_optimal"
        q4_ans = (
            f"Per-series local and zero-shot models are optimal for "
            f"scale_regime='{self.profile.scale_regime}' (n_series={self.profile.n_series}, "
            f"corr={self.profile.cross_series_corr:.2f}), avoiding global neural overfitting."
            f"{sim_note}{donor_note}"
        )
    q4_ev = (
        f"n_series={self.profile.n_series}, scale_regime='{self.profile.scale_regime}', "
        f"cross_series_corr={self.profile.cross_series_corr:.2f}, "
        f"optimal_similarity_clusters={opt_k}, similarity_silhouette_score={sim_sil:.2f}, "
        f"global_models={global_models}, cold_start_transfer={cs_transfer_on}, "
        f"cold_start_donor_similarity={donor_sim:.2f}"
    )

    # 5. Is reconciliation being done correctly?
    sim_hier_on = bool(getattr(champ.config.hierarchy, "similarity_hierarchy", False))
    has_spatial = bool(
        self.profile.hierarchy_id_cols
        or sim_hier_on
        or (champ.config.hierarchy.enabled and (champ.config.hierarchy.levels or sim_hier_on))
    )
    has_temporal = bool(
        champ.config.hierarchy.reconcile_temporal
        or champ.config.hierarchy.cross_temporal
        or "cross_temporal_mint" in champ.config.hierarchy.reconciliation_methods
        or diag.get("reconciliation_mode") in ("temporal_only", "cross_temporal")
    )
    temp_aggs = list(
        champ.config.hierarchy.temporal_aggregations
        or getattr(self.profile, "temporal_aggregations", None)
        or [1]
    )
    is_simplex = bool(
        getattr(self.profile, "is_compositional_simplex", False)
        or champ.config.features.simplex_sum is not None
        or champ.config.features.transform in ("clr", "ilr")
        or any("@transform_clr" in m or "@transform_ilr" in m for m in champ.config.models)
    )

    if has_spatial and has_temporal:
        all_row = (
            hval_df[hval_df["hierarchy_level"] == "All Hierarchy Nodes"]
            if not hval_df.empty
            else pd.DataFrame()
        )
        r_row = (
            all_row.iloc[0]
            if not all_row.empty
            else (hval_df.iloc[0] if not hval_df.empty else pd.Series(dtype=object))
        )
        max_coh = float(
            r_row.get("max_coherence_residual", diag.get("spatial_coherence_residual", 0.0))
        )
        temp_coh = float(
            r_row.get(
                "temporal_coherence_residual", diag.get("temporal_coherence_residual", 0.0)
            )
        )
        neg_cnt = int(r_row.get("negative_leaf_count", 0))
        rec_m = str(r_row.get("reconciliation_method", "cross_temporal_mint"))
        rec_lift = float(r_row.get("reconciliation_lift_pct", 0.0))
        alpha_val = diag.get(
            "spatial_weight_alpha", champ.config.hierarchy.spatial_temporal_weight
        )
        alpha_str = (
            f"{float(alpha_val):.4f}"
            if isinstance(alpha_val, (int, float)) and not isinstance(alpha_val, bool)
            else str(alpha_val)
        )
        ct_beat = bool(
            diag.get(
                "cross_temporal_beats_spatial",
                "cross_temporal_mint" in str(champ.champion_model),
            )
        )
        q5_verdict = (
            "coherent_and_verified"
            if max_coh < 1e-4 and temp_coh < 1e-4 and neg_cnt == 0
            else "check_tree"
        )
        q5_ans = (
            f"Yes — cross_temporal reconciliation ('{rec_m}', mode=cross_temporal, "
            f"similarity_hierarchy={sim_hier_on}) achieved exact spatial coherence "
            f"(residual={max_coh:.6f}) and temporal coherence "
            f"(residual={temp_coh:.6f} across aggregations={temp_aggs}, "
            f"spatial_weight_alpha={alpha_str}), {neg_cnt} negative leaves, "
            f"{rec_lift:+.2f}% tree-wide accuracy change, and "
            f"cross_temporal_beats_spatial={ct_beat}."
        )
        q5_ev = (
            f"mode='cross_temporal', method='{rec_m}', coherence_gap={max_coh:.6f}, "
            f"temporal_coherence_gap={temp_coh:.6f}, temporal_aggregations={temp_aggs}, "
            f"spatial_weight_alpha={alpha_str}, cross_temporal_beats_spatial={ct_beat}, "
            f"similarity_hierarchy={sim_hier_on}, negative_leaves={neg_cnt}, "
            f"levels={len(hval_df)}"
        )
    elif has_spatial and not hval_df.empty:
        all_row = hval_df[hval_df["hierarchy_level"] == "All Hierarchy Nodes"]
        r_row = all_row.iloc[0] if not all_row.empty else hval_df.iloc[0]
        max_coh = float(r_row.get("max_coherence_residual", 0.0))
        neg_cnt = int(r_row.get("negative_leaf_count", 0))
        rec_m = str(r_row.get("reconciliation_method", "mint_nonneg"))
        rec_lift = float(r_row.get("reconciliation_lift_pct", 0.0))
        q5_verdict = (
            "coherent_and_verified" if max_coh < 1e-4 and neg_cnt == 0 else "check_tree"
        )
        q5_ans = (
            f"Yes — fold-safe '{rec_m}' spatial_only reconciliation "
            f"(similarity_hierarchy={sim_hier_on}) achieved exact additive "
            f"coherence (residual={max_coh:.6f}), {neg_cnt} negative leaves, and "
            f"{rec_lift:+.2f}% tree-wide accuracy change."
        )
        q5_ev = (
            f"mode='spatial_only', method='{rec_m}', coherence_gap={max_coh:.6f}, "
            f"similarity_hierarchy={sim_hier_on}, negative_leaves={neg_cnt}, "
            f"levels={len(hval_df)}"
        )
    elif has_temporal:
        all_row = (
            hval_df[hval_df["hierarchy_level"] == "All Hierarchy Nodes"]
            if not hval_df.empty
            else pd.DataFrame()
        )
        r_row = (
            all_row.iloc[0]
            if not all_row.empty
            else (hval_df.iloc[0] if not hval_df.empty else pd.Series(dtype=object))
        )
        temp_coh = float(
            r_row.get(
                "temporal_coherence_residual",
                r_row.get(
                    "max_coherence_residual", diag.get("temporal_coherence_residual", 0.0)
                ),
            )
        )
        rec_m = str(
            r_row.get(
                "reconciliation_method",
                champ.config.hierarchy.reconciliation_methods[0]
                if champ.config.hierarchy.reconciliation_methods
                else "wls_struct",
            )
        )
        rec_lift = float(r_row.get("reconciliation_lift_pct", 0.0))
        q5_verdict = "temporal_coherent_and_verified" if temp_coh < 1e-4 else "check_temporal"
        q5_ans = (
            f"Yes — temporal_only reconciliation ('{rec_m}') on flat panel verified exact "
            f"multi-horizon bucket coherence (temporal_residual={temp_coh:.6f} across "
            f"temporal_aggregations={temp_aggs}, similarity_hierarchy={sim_hier_on}) "
            f"with {rec_lift:+.2f}% accuracy change."
        )
        q5_ev = (
            f"mode='temporal_only', method='{rec_m}', temporal_coherence_gap={temp_coh:.6f}, "
            f"temporal_aggregations={temp_aggs}, similarity_hierarchy={sim_hier_on}, "
            f"reconciliation_lift_pct={rec_lift:+.2f}%"
        )
    else:
        q5_verdict = "not_applicable_flat_panel"
        q5_ans = (
            "Flat panel (no explicit hierarchy columns; "
            f"similarity_hierarchy={sim_hier_on}, similarity_clusters={opt_k}); "
            "output.floor enforces non-negativity directly."
        )
        q5_ev = (
            f"mode='none', hierarchy_id_cols={list(self.profile.hierarchy_id_cols)}, "
            f"similarity_hierarchy={sim_hier_on}, optimal_similarity_clusters={opt_k}"
        )

    if is_simplex:
        from .simplex import verify_simplex_coherence

        s_target = float(
            champ.config.features.simplex_sum
            or getattr(self.profile, "simplex_total", None)
            or 1.0
        )
        simplex_disc = (
            float(
                verify_simplex_coherence(
                    self.predictions_df,
                    simplex_sum=s_target,
                    raise_on_error=False,
                )
            )
            if not self.predictions_df.empty
            else 0.0
        )
        min_share = (
            float(pd.to_numeric(self.predictions_df["yhat"], errors="coerce").min())
            if not self.predictions_df.empty and "yhat" in self.predictions_df.columns
            else s_target
        )
        q5_ans += (
            f" Compositional simplex closure active (simplex_sum={s_target:g}, "
            f"simplex_discrepancy={simplex_disc:.6f}, min_share={min_share:.6f} > 0)."
        )
        q5_ev += (
            f", is_compositional_simplex=True, simplex_sum={s_target:g}, "
            f"simplex_discrepancy={simplex_disc:.6f}, strictly_positive={min_share > 0.0}"
        )
        if not has_spatial and not has_temporal:
            q5_verdict = (
                "coherent_and_verified"
                if simplex_disc < 1e-4 and min_share > 0.0
                else "check_simplex"
            )

    # 6. Does accuracy hold up across the horizon?
    decay_ratio = float(diag.get("late_horizon_degradation_ratio", 1.0))
    crossover_h = diag.get("horizon_crossover_step")
    has_hz_spec = "horizon_specialist" in champ.config.ensemble.strategies or any(
        "@direct" in m for m in champ.config.models
    )
    if decay_ratio <= 1.35:
        q6_verdict = "stable_across_horizon"
        q6_ans = (
            f"Forecast error remains stable from step 1 to {self.profile.horizon} "
            f"(late/early ratio={decay_ratio:.2f}x)."
        )
    else:
        q6_verdict = "horizon_specialist_mitigated" if has_hz_spec else "late_horizon_decay"
        q6_ans = (
            f"Late-horizon error grows {decay_ratio:.2f}x vs. early steps "
            f"(crossover step={crossover_h}); "
            + (
                "mitigated via @direct horizon models and horizon_specialist blending."
                if has_hz_spec
                else "consider enabling @direct models or horizon_specialist ensembling."
            )
        )
    q6_ev = (
        f"late_early_ratio={decay_ratio:.2f}, crossover_step={crossover_h}, "
        f"direct_or_specialist={has_hz_spec}"
    )

    # 7. How do I trust the forecast?
    p1_sc = self.passes[0].champion_score
    tot_gain = (
        round(100.0 * (p1_sc - champ.champion_score) / max(1e-9, p1_sc), 2)
        if len(self.passes) > 1 and math.isfinite(p1_sc) and p1_sc > 1e-9
        else 0.0
    )
    acf1 = float(diag.get("residual_autocorr_lag1", 0.0))
    biased_share = float(diag.get("biased_series_share", 0.0))
    cal_method = str(getattr(champ.config.output, "calibration_method", "conformal"))
    aci_gamma_val = float(getattr(champ.config.output, "aci_gamma", 0.05))
    ks_drift_val = float(
        diag.get(
            "residual_drift_ks_stat",
            getattr(self.profile, "residual_drift_ks_stat", 0.0),
        )
    )
    q7_verdict = (
        "high_confidence" if fva_naive > 0.0 and biased_share < 0.25 else "review_exceptions"
    )
    q7_ans = (
        f"Evaluated on {champ.config.backtest.n_folds} rolling out-of-fold backtest window(s) "
        f"with {cal_method} prediction intervals (aci_gamma={aci_gamma_val:.3f}), "
        f"Champion Ratchet protection (Pass {champ.pass_id} won, +{tot_gain:.2f}% over "
        f"Pass 1), residual ACF1={acf1:.2f}, drift KS={ks_drift_val:.2f}, and copula "
        f"tail_risk Audit."
    )
    q7_ev = (
        f"n_folds={champ.config.backtest.n_folds}, calibration_method='{cal_method}', "
        f"aci_gamma={aci_gamma_val:.3f}, champion_pass={champ.pass_id}/{len(self.passes)}, "
        f"residual_acf1={acf1:.2f}, residual_drift_ks_stat={ks_drift_val:.2f}, "
        f"biased_series_share={biased_share:.1%}, tail_risk_ready=True"
    )

    rows = [
        {
            "question_id": "model_vs_baseline",
            "question": "1. Is the winning model genuinely better than simple baselines?",
            "verdict": q1_verdict,
            "answer": q1_ans,
            "evidence": q1_ev,
            "recommendation": (
                "Inspect f.baseline_value_df() and f.compare_models() for pairwise win rates."
            ),
        },
        {
            "question_id": "ensemble_vs_single",
            "question": "2. Do ensembles help here, or is a single model better?",
            "verdict": q2_verdict,
            "answer": q2_ans,
            "evidence": q2_ev,
            "recommendation": (
                "Ensembles must beat the best single model by the parsimony margin "
                "to be crowned."
            ),
        },
        {
            "question_id": "covariates_vs_overfitting",
            "question": "3. Do covariates help, or are they just overfitting noise?",
            "verdict": q3_verdict,
            "answer": q3_ans,
            "evidence": q3_ev,
            "recommendation": (
                "Inspect f.attributions_df() and f.promo_elasticity_df() to see per-feature "
                "importance shares, promotional lift, and causal sign adherence."
            ),
        },
        {
            "question_id": "global_vs_local",
            "question": "4. Does cross-series @global training beat per-series @local fitting?",
            "verdict": q4_verdict,
            "answer": q4_ans,
            "evidence": q4_ev,
            "recommendation": (
                "Global pooling pays off most when n_series >= 15 or "
                "cross_series_corr >= 0.35; inspect f.cold_start_transfer_df() when "
                "cold_start series are present."
            ),
        },
        {
            "question_id": "hierarchy_reconciliation",
            "question": (
                "5. Is hierarchical reconciliation coherent, non-negative, and accurate?"
            ),
            "verdict": q5_verdict,
            "answer": q5_ans,
            "evidence": q5_ev,
            "recommendation": (
                "Inspect f.hierarchy_value_df() for Root, Intermediate, and Leaf accuracy lift."
            ),
        },
        {
            "question_id": "horizon_stability",
            "question": "6. Does accuracy hold up across the whole forecast horizon?",
            "verdict": q6_verdict,
            "answer": q6_ans,
            "evidence": q6_ev,
            "recommendation": (
                "Inspect f.horizon_decay_df() for step-by-step error from h=1..H."
            ),
        },
        {
            "question_id": "forecast_trust",
            "question": "7. How do I trust this forecast in production?",
            "verdict": q7_verdict,
            "answer": q7_ans,
            "evidence": q7_ev,
            "recommendation": (
                "Inspect f.aci_df(), f.tail_risk_df(), and f.explain_auto_decisions_df() "
                "for online ACI coverage, copula tail_risk, and the Glass-Box audit trail."
            ),
        },
    ]
    _ = bval_df
    return pd.DataFrame(rows, columns=cols)

profile_df

profile_df()

Return the 7-row Step 0 Data Profile & Readiness DataFrame for this session.

Source code in src/scale_forecasting/auto.py
def profile_df(self) -> pd.DataFrame:
    """Return the 7-row Step 0 Data Profile & Readiness ``DataFrame`` for this session."""
    return self.profile.to_df()

promo_elasticity_df

promo_elasticity_df(
    *,
    data=None,
    promo_col=None,
    price_col=None,
    confounders=None,
    summary=False,
)

Compute cross-fitted Double-ML promo & price elasticity decomposition on this session's panel (elasticity.compute_promo_elasticity_decomposition).

Source code in src/scale_forecasting/auto.py
def promo_elasticity_df(
    self,
    *,
    data: pd.DataFrame | None = None,
    promo_col: str | None = None,
    price_col: str | None = None,
    confounders: Sequence[str] | None = None,
    summary: bool = False,
) -> pd.DataFrame:
    """Compute cross-fitted Double-ML promo & price elasticity decomposition on this session's
    panel (`elasticity.compute_promo_elasticity_decomposition`).
    """
    from .elasticity import compute_promo_elasticity_decomposition, summarize_promo_elasticity

    panel = data if data is not None else self.data_df
    if panel is None or panel.empty:
        return pd.DataFrame()
    champ = self.champion_record()
    cfg = champ.config if champ is not None else self.blueprint.config
    decomp = compute_promo_elasticity_decomposition(
        panel,
        ts_id_col=cfg.data.ts_id_col,
        date_col=cfg.data.date_col,
        target_col=cfg.data.target_col,
        promo_col=promo_col,
        price_col=price_col,
        confounders=confounders,
        freq=cfg.data.freq,
        holidays=cfg.features.holidays,
    )
    return summarize_promo_elasticity(decomp) if summary else decomp

simulate_scenarios

simulate_scenarios(
    scenarios,
    *,
    data=None,
    models=None,
    future_covariates_df=None,
    price_col=None,
    unit_cost=None,
    reconcile=True,
    include_inventory_impact=False,
    lead_time=7.0,
    lead_time_std=0.0,
    service_level=0.95,
    inventory_params=None,
)

Run full-chain counterfactual scenario propagation across this session's champion configuration (base models -> ensembles -> hierarchy reconciliation -> gross margin & inventory policy shift).

Source code in src/scale_forecasting/auto.py
def simulate_scenarios(
    self,
    scenarios: Mapping[str, Mapping[str, Any]],
    *,
    data: pd.DataFrame | None = None,
    models: Sequence[str] | None = None,
    future_covariates_df: pd.DataFrame | None = None,
    price_col: str | None = None,
    unit_cost: float | str | Mapping[str, float] | None = None,
    reconcile: bool = True,
    include_inventory_impact: bool = False,
    lead_time: float = 7.0,
    lead_time_std: float = 0.0,
    service_level: float = 0.95,
    inventory_params: Mapping[str, Any] | None = None,
) -> pd.DataFrame:
    """Run full-chain counterfactual scenario propagation across this session's champion
    configuration (base models -> ensembles -> hierarchy reconciliation -> gross margin &
    inventory policy shift).
    """
    from .scenarios import simulate_scenarios

    panel = data if data is not None else self.data_df
    if panel is None or panel.empty:
        raise DataError("No in-memory panel available on AutoForecastSession; pass data=...")
    champ = self.champion_record()
    cfg = champ.config if champ is not None else self.blueprint.config
    fut = future_covariates_df if future_covariates_df is not None else self.future_df
    oof = self.oof_df if not self.oof_df.empty else None
    return simulate_scenarios(
        panel,
        cfg,
        scenarios,
        models=models,
        future_covariates_df=fut,
        price_col=price_col,
        unit_cost=unit_cost,
        reconcile=reconcile,
        include_inventory_impact=include_inventory_impact,
        lead_time=lead_time,
        lead_time_std=lead_time_std,
        service_level=service_level,
        oof_df=oof,
        inventory_params=inventory_params,
    )

AutofocusPassRecord dataclass

AutofocusPassRecord(
    pass_index,
    run_id,
    tier,
    models_total,
    models_borrowed,
    models_executed,
    champion_model,
    decision_metric,
    champion_score,
    fva_vs_naive_pct,
    dm_pvalue,
    predicted_p50_s,
    actual_wall_s,
    continue_confidence,
    expected_next_gain_pct,
    mutations_applied,
    stop_or_continue_reason,
    config,
    pass_id="1",
    parent_pass_ids=(),
    branch_hypothesis="Initial Tier Exposure",
    mutations_detail=(),
    is_session_champion=False,
    fva_vs_univariate_pct=0.0,
    fva_vs_foundation_pct=0.0,
    covariate_lift_pct=0.0,
    reconciliation_lift_pct=0.0,
    champion_is_univariate=False,
    beaten_challengers=(),
)

Audit record for one executed pass or Tournament DAG branch in a closed-loop autofocus.

best_model property

best_model

Alias for champion_model.

best_score property

best_score

Alias for champion_score.

ConfigBlueprint dataclass

ConfigBlueprint(
    config,
    profile,
    tier,
    where,
    goal,
    rationale_df,
    duration_estimate,
    cost_estimate_usd,
    baselines=(),
)

Glass-Box compilation output: a standard RunConfig plus every empirical rationale.

estimated_minutes_p50 property

estimated_minutes_p50

Predicted P50 wall-clock duration in minutes.

estimated_minutes_p90 property

estimated_minutes_p90

Predicted P90 wall-clock duration in minutes.

rationale property

rationale

Dictionary mapping parameter -> rationale for every synthesized decision.

run_id property

run_id

Deterministic content-addressed run_id for the compiled RunConfig.

emit_airflow_dag

emit_airflow_dag(
    config_uri=None,
    *,
    out_path=None,
    autofocus=False,
    autofocus_mode="dag",
    max_passes=3,
    with_retry=False,
    dag_id=None,
)

Render this blueprint as a standalone Cloud Composer 3 / Airflow DAG Python string.

When autofocus=False (default), renders the standard per-family parallel execution DAG (emit_airflow_dag). When autofocus=True, renders the multi-pass autofocus tournament DAG (emit_autofocus_airflow_dag: `autofocus_pass_1 >> [branch_2a, branch_2b, branch_2c]

autofocus_pass_3_synthesis`). If out_path is supplied, writes the rendered source to disk as well.

Source code in src/scale_forecasting/auto.py
def emit_airflow_dag(
    self,
    config_uri: str | Path | None = None,
    *,
    out_path: str | Path | None = None,
    autofocus: bool = False,
    autofocus_mode: str = "dag",
    max_passes: int = 3,
    with_retry: bool = False,
    dag_id: str | None = None,
) -> str:
    """Render this blueprint as a standalone Cloud Composer 3 / Airflow DAG Python string.

    When ``autofocus=False`` (default), renders the standard per-family parallel execution DAG
    (`emit_airflow_dag`). When ``autofocus=True``, renders the multi-pass `autofocus` tournament
    DAG (`emit_autofocus_airflow_dag`: `autofocus_pass_1 >> [branch_2a, branch_2b, branch_2c]
    >> autofocus_pass_3_synthesis`). If ``out_path`` is supplied, writes the rendered source to
    disk as well.
    """
    from .airflow_emit import emit_airflow_dag, emit_autofocus_airflow_dag

    uri = str(config_uri or f"auto_{self.run_id}.json")
    if autofocus:
        source = emit_autofocus_airflow_dag(
            self.config,
            uri,
            tier=self.tier,
            where=self.where,
            goal=self.goal,
            autofocus_mode=autofocus_mode,
            max_passes=max_passes,
            dag_id=dag_id,
        )
    else:
        source = emit_airflow_dag(
            self.config,
            uri,
            dag_id=dag_id,
            with_retry=with_retry,
        )
    if out_path is not None:
        p = Path(out_path)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(source, encoding="utf-8")
    return source

explain

explain()

Return a human-readable summary plus the field-by-field rationale table.

Source code in src/scale_forecasting/auto.py
def explain(self) -> str:
    """Return a human-readable summary plus the field-by-field rationale table."""
    table_str = (
        self.rationale_df.to_string(index=False)
        if not self.rationale_df.empty
        else "(no rationale entries)"
    )
    return f"{self.summary()}\n\n{table_str}"

profile_df

profile_df()

Return the 7-row Step 0 Data Profile & Readiness DataFrame for this panel.

Source code in src/scale_forecasting/auto.py
def profile_df(self) -> pd.DataFrame:
    """Return the 7-row Step 0 Data Profile & Readiness ``DataFrame`` for this panel."""
    return self.profile.to_df()

summary

summary()

Human-readable summary of the compiled Glass-Box blueprint.

Source code in src/scale_forecasting/auto.py
def summary(self) -> str:
    """Human-readable summary of the compiled Glass-Box blueprint."""
    tier_title = EXPOSURE_TIERS.get(self.tier, {}).get("title", self.tier)
    baseline_str = (
        ", ".join(f"{b['model_type']} ({b['baseline_role']})" for b in self.baselines)
        if self.baselines
        else "naive_seasonal"
    )
    lines = [
        f"Glass-Box Blueprint : {self.config.run_name} ({self.run_id})",
        f"Exposure Tier       : {self.tier} ({tier_title})",
        (
            f"Sandbox Envelope    : where='{self.where}' | goal='{self.goal}' | "
            f"scale='{self.profile.scale_regime}'"
        ),
        (
            f"Panel Profile       : {self.profile.n_series} series | "
            f"freq='{self.profile.freq}' | median_T={self.profile.median_n_obs} | "
            f"H={self.profile.horizon} | regime='{self.profile.dominant_regime}'"
        ),
        f"Baseline Ladder     : {baseline_str}",
        f"Selected Models ({len(self.config.models)}) : {', '.join(self.config.models)}",
        f"Predicted Duration  : {self.duration_estimate.summary()}",
    ]
    return "\n".join(lines)

to_dict

to_dict()

Serialize blueprint to a plain JSON-friendly dictionary.

Source code in src/scale_forecasting/auto.py
def to_dict(self) -> dict[str, Any]:
    """Serialize blueprint to a plain JSON-friendly dictionary."""
    return {
        "run_id": self.run_id,
        "tier": self.tier,
        "where": self.where,
        "goal": self.goal,
        "scale_regime": self.profile.scale_regime,
        "baselines": [dict(b) for b in self.baselines],
        "cost_estimate_usd": round(self.cost_estimate_usd, 4),
        "duration_estimate": self.duration_estimate.to_dict(),
        "profile": self.profile.to_dict(),
        "rationale": self.rationale_df.to_dict(orient="records"),
        "config": self.config.model_dump(mode="json"),
    }

to_file

to_file(path, *, indent=2)

Write the compiled RunConfig JSON to path and return its Path.

Source code in src/scale_forecasting/auto.py
def to_file(self, path: str | Any, *, indent: int = 2) -> Any:
    """Write the compiled `RunConfig` JSON to ``path`` and return its ``Path``."""
    out_path = Path(path)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(self.to_json(indent=indent) + "\n", encoding="utf-8")
    return out_path

to_json

to_json(*, indent=2)

Serialize the compiled RunConfig to a formatted JSON string.

Source code in src/scale_forecasting/auto.py
def to_json(self, *, indent: int = 2) -> str:
    """Serialize the compiled `RunConfig` to a formatted JSON string."""
    return json.dumps(self.config.model_dump(mode="json"), indent=indent)

with_overrides

with_overrides(**kwargs)

Return a new :class:ConfigBlueprint with user constraint overrides applied.

Re-uses self.profile (zero re-profiling cost) and accepts any :func:build_config keyword argument (tier, where, goal, allowed_families, models, include_models, exclude_models, baselines, holidays, decision_metric, n_folds, hpo, ensemble, explainability, max_minutes, max_usd, overrides, etc.).

Source code in src/scale_forecasting/auto.py
def with_overrides(self, **kwargs: Any) -> ConfigBlueprint:
    """Return a new :class:`ConfigBlueprint` with user constraint overrides applied.

    Re-uses ``self.profile`` (zero re-profiling cost) and accepts any :func:`build_config`
    keyword argument (`tier`, `where`, `goal`, `allowed_families`, `models`, `include_models`,
    `exclude_models`, `baselines`, `holidays`, `decision_metric`, `n_folds`, `hpo`, `ensemble`,
    `explainability`, `max_minutes`, `max_usd`, `overrides`, etc.).
    """
    call_kwargs: dict[str, Any] = {
        "tier": kwargs.pop("tier", self.tier),
        "where": kwargs.pop("where", self.where),
        "goal": kwargs.pop("goal", self.goal),
        "base_config": kwargs.pop("base_config", self.config),
    }
    valid_build_keys = {
        "allowed_families",
        "overrides",
        "models",
        "include_models",
        "exclude_models",
        "baselines",
        "holidays",
        "decision_metric",
        "n_folds",
        "hpo",
        "ensemble",
        "explainability",
        "calibration",
        "max_minutes",
        "max_wall_clock_minutes",
        "max_usd",
        "future_df",
        "ts_id_col",
        "date_col",
        "target_col",
        "freq",
        "horizon",
        "run_name",
        "only_available_models",
        "settings",
    }
    extra_overrides = dict(kwargs.pop("overrides", {}) or {})
    for k in list(kwargs.keys()):
        if k not in valid_build_keys:
            extra_overrides[k] = kwargs.pop(k)
    if extra_overrides:
        call_kwargs["overrides"] = extra_overrides
    call_kwargs.update(kwargs)
    return build_config(self.profile, **call_kwargs)

NextLoopPreview dataclass

NextLoopPreview(
    next_pass_index,
    should_continue,
    confidence,
    expected_gain_pct,
    reason,
    proposed_config,
    mutations_df,
    borrowed_models,
    new_models_to_fit,
    duration_estimate,
    branches=(),
)

Dry-run preview of what the next autofocus pass ($k+1$) or DAG branches would execute.

stop_reason property

stop_reason

Alias for reason.

to_dataframe

to_dataframe()

Return a summary DataFrame of the next-loop preview (1 row per proposed branch).

Source code in src/scale_forecasting/auto.py
def to_dataframe(self) -> pd.DataFrame:
    """Return a summary DataFrame of the next-loop preview (1 row per proposed branch)."""
    if len(self.branches) > 1:
        rows = [
            {
                "next_pass_index": self.next_pass_index,
                "pass_id": b.get("pass_id", str(self.next_pass_index)),
                "branch_hypothesis": b.get("branch_hypothesis", ""),
                "should_continue": self.should_continue,
                "confidence": self.confidence,
                "expected_gain_pct": self.expected_gain_pct,
                "borrowed_models": ", ".join(self.borrowed_models)
                if self.borrowed_models
                else "(none)",
                "new_models_to_fit": ", ".join(b.get("added_models", ())) or "(feature_update)",
                "predicted_p50_seconds": round(self.duration_estimate.total_p50_seconds, 2),
                "reason": self.reason,
            }
            for b in self.branches
        ]
        return pd.DataFrame(rows)
    return pd.DataFrame(
        [
            {
                "next_pass_index": self.next_pass_index,
                "pass_id": str(self.next_pass_index),
                "branch_hypothesis": (
                    self.branches[0].get("branch_hypothesis", "Targeted Refinement")
                    if self.branches
                    else "None"
                ),
                "should_continue": self.should_continue,
                "confidence": self.confidence,
                "expected_gain_pct": self.expected_gain_pct,
                "borrowed_models": ", ".join(self.borrowed_models)
                if self.borrowed_models
                else "(none)",
                "new_models_to_fit": ", ".join(self.new_models_to_fit)
                if self.new_models_to_fit
                else "(none)",
                "predicted_p50_seconds": round(self.duration_estimate.total_p50_seconds, 2),
                "reason": self.reason,
            }
        ]
    )

to_dict

to_dict()

Serialize next-loop preview to a JSON-compatible dictionary.

Source code in src/scale_forecasting/auto.py
def to_dict(self) -> dict[str, Any]:
    """Serialize next-loop preview to a JSON-compatible dictionary."""
    return {
        "next_pass_index": self.next_pass_index,
        "should_continue": self.should_continue,
        "confidence": self.confidence,
        "expected_gain_pct": self.expected_gain_pct,
        "reason": self.reason,
        "borrowed_models": list(self.borrowed_models),
        "new_models_to_fit": list(self.new_models_to_fit),
        "branch_count": max(1, len(self.branches)) if self.should_continue else 0,
        "duration_estimate": self.duration_estimate.to_dict(),
        "mutations": self.mutations_df.to_dict(orient="records"),
        "proposed_config": self.proposed_config.model_dump(mode="json"),
    }

PanelAutoProfile dataclass

PanelAutoProfile(
    source_table,
    ts_id_col,
    date_col,
    target_col,
    freq,
    horizon,
    n_series,
    n_rows,
    median_n_obs,
    min_n_obs,
    max_n_obs,
    non_negative,
    integer_valued,
    zero_fraction,
    median_adi,
    median_cv2,
    level_vol_corr,
    end_to_start_ratio,
    dominant_regime,
    regime_shares=dict(),
    median_acf_season=0.0,
    structural_break_share=0.0,
    outlier_spike_share=0.0,
    future_covariates=(),
    past_covariates=(),
    static_covariates=(),
    hierarchy_id_cols=(),
    censored_col=None,
    leading_zero_share=0.0,
    missing_date_gap_share=0.0,
    hierarchy_node_count=0,
    cross_series_corr=0.0,
    monotonic_constraints=dict(),
    is_compositional_simplex=False,
    simplex_total=0.0,
    cold_start_donor_similarity=0.0,
    residual_drift_ks_stat=0.0,
    mean_pairwise_similarity=0.0,
    optimal_similarity_clusters=1,
    similarity_silhouette_score=0.0,
    lead_lag_pairs_count=0,
    has_similarity_clusters=False,
    dominant_cluster_archetype="steady_baseline",
)

Single-pass statistical and structural profile of a time-series panel (pure).

scale_regime property

scale_regime

Canonical series-count scale regime (micro .. hyperscale).

explain

explain()

Return a formatted text summary of the Step 0 Data Profile & Readiness table.

Source code in src/scale_forecasting/auto_policy.py
def explain(self) -> str:
    """Return a formatted text summary of the Step 0 Data Profile & Readiness table."""
    df = self.to_df()
    header = (
        f"Step 0 Data Profile : {self.source_table} | {self.n_series} series "
        f"({self.scale_regime}) | freq='{self.freq}' | H={self.horizon}"
    )
    return f"{header}\n\n{df.to_string(index=False)}"

from_df classmethod

from_df(data, **kwargs)

Profile an in-memory DataFrame or BigQuery table via :func:inspect_panel_for_auto.

Source code in src/scale_forecasting/auto_policy.py
@classmethod
def from_df(cls, data: Any, **kwargs: Any) -> PanelAutoProfile:
    """Profile an in-memory DataFrame or BigQuery table via :func:`inspect_panel_for_auto`."""
    from .auto import inspect_panel_for_auto

    return inspect_panel_for_auto(data, **kwargs)

to_df

to_df()

Return a 7-row Step 0 Data Profile & Readiness DataFrame for human review.

Source code in src/scale_forecasting/auto_policy.py
def to_df(self) -> Any:
    """Return a 7-row Step 0 Data Profile & Readiness ``DataFrame`` for human review."""
    import pandas as pd

    scale_info = SCALE_REGIMES.get(self.scale_regime, SCALE_REGIMES["small"])
    cold_share = float(self.regime_shares.get("cold_start", 0.0))
    cov_list = (
        list(self.future_covariates) + list(self.past_covariates) + list(self.static_covariates)
    )
    rows = [
        {
            "dimension": "scale_and_shape",
            "signal": "n_series · history · scale_regime · cross_series_corr · similarity",
            "measured_value": (
                f"{self.n_series} series ({self.scale_regime}) | "
                f"freq='{self.freq}' | median_T={self.median_n_obs} "
                f"(min={self.min_n_obs}, max={self.max_n_obs}) | H={self.horizon} | "
                f"corr={self.cross_series_corr:.2f} | "
                f"sim={self.mean_pairwise_similarity:.2f} "
                f"(K={self.optimal_similarity_clusters}, "
                f"sil={self.similarity_silhouette_score:.2f})"
            ),
            "implication": str(scale_info["strategy"]),
        },
        {
            "dimension": "demand_regime",
            "signal": "dominant_regime · zero_fraction · ADI · CV² · cold_start",
            "measured_value": (
                f"regime='{self.dominant_regime}' | zeros={self.zero_fraction:.1%} | "
                f"ADI={self.median_adi:.2f} | CV²={self.median_cv2:.2f} | "
                f"cold_start={cold_share:.1%} | "
                f"donor_sim={self.cold_start_donor_similarity:.2f}"
            ),
            "implication": (
                "Intermittent/lumpy zeros trigger MASE scoring and Croston/TSB specialists "
                "with regime routing."
                if (
                    self.zero_fraction >= 0.25
                    or self.dominant_regime in ("intermittent", "lumpy")
                )
                else (
                    "Mixed mature and short cold-start series favor cross-series pooling and "
                    "SBC regime routing."
                    if cold_share > 0.05
                    else (
                        "Smooth/continuous series support WAPE scoring and standard "
                        "lag/seasonal models."
                    )
                )
            ),
        },
        {
            "dimension": "seasonality_and_scaling",
            "signal": "seasonal_acf · level_vol_corr · end_to_start_ratio",
            "measured_value": (
                f"acf_season={self.median_acf_season:.2f} | "
                f"level_vol_corr={self.level_vol_corr:.2f} | "
                f"growth_ratio={self.end_to_start_ratio:.2f}"
            ),
            "implication": (
                "Amplitude scales with level (multiplicative); log1p variance stabilization "
                "recommended."
                if (self.level_vol_corr >= 0.55 and self.end_to_start_ratio >= 1.35)
                else (
                    "Additive variance regime; standard linear target scaling is "
                    "well-conditioned."
                )
            ),
        },
        {
            "dimension": "breaks_and_outliers",
            "signal": "structural_break_share · outlier_spike_share",
            "measured_value": (
                f"breaks={self.structural_break_share:.1%} | "
                f"spikes={self.outlier_spike_share:.1%} | "
                f"ks_drift={self.residual_drift_ks_stat:.2f}"
            ),
            "implication": (
                "Elevated structural shifts or >6-sigma spikes trigger level_shift indicators "
                "and fold-safe stl_resid outlier scrubbing."
                if (self.structural_break_share >= 0.15 or self.outlier_spike_share >= 0.10)
                else (
                    "Clean historical trajectory; no aggressive outlier clipping required "
                    "in Pass 1."
                )
            ),
        },
        {
            "dimension": "hygiene_and_calendar",
            "signal": "leading_zeros · missing_gaps · censored_col",
            "measured_value": (
                f"leading_zeros={self.leading_zero_share:.1%} | "
                f"date_gaps={self.missing_date_gap_share:.1%} | "
                f"censored_col={self.censored_col or 'none'}"
            ),
            "implication": (
                "Pre-launch leading zeros, calendar gaps, or stockout censoring detected; "
                "enables automatic hygiene repair / latent demand reconstruction."
                if (
                    self.leading_zero_share >= 0.05
                    or self.missing_date_gap_share > 0.0
                    or self.censored_col
                )
                else "Contiguous date grid with no pre-launch zero padding or stockout flags."
            ),
        },
        {
            "dimension": "covariates",
            "signal": "future · past · static covariates",
            "measured_value": (
                f"{len(cov_list)} column(s): {', '.join(cov_list)}"
                if cov_list
                else "0 extra feature columns (pure univariate panel)"
            ),
            "implication": (
                "Benchmarks covariate models (@cov_all) against paired @univariate baselines "
                "and prunes low-attribution decoy columns in autofocus."
                if cov_list
                else "Univariate panel; prioritizes seasonal, state-space, lag-tree, and "
                "univariate foundation models."
            ),
        },
        {
            "dimension": "hierarchy_topology",
            "signal": "hierarchy_id_cols · node_count · non_negative · similarity_clusters",
            "measured_value": (
                f"cols={list(self.hierarchy_id_cols)} | "
                f"nodes={max(self.hierarchy_node_count, self.n_series)} | "
                f"non_negative={self.non_negative}"
                if self.hierarchy_id_cols
                else (
                    f"Flat panel (no hierarchy columns) | "
                    f"similarity_clusters={self.optimal_similarity_clusters} "
                    f"(sil={self.similarity_silhouette_score:.2f}) | "
                    f"non_negative={self.non_negative}"
                )
            ),
            "implication": (
                "Hierarchical tree detected; applies scale-aware coherent reconciliation "
                f"({', '.join(select_hierarchy_reconciliation_methods(self))}) with 0.0 "
                "aggregation residual."
                if self.hierarchy_id_cols
                else (
                    "Flat panel with distinct behavioral similarity clusters; supports "
                    "@similarity_global pooling and latent similarity_hierarchy reconciliation."
                    if self.has_similarity_clusters
                    else (
                        "Independent series; enforces output.floor=0.0 when history "
                        "is non-negative."
                    )
                )
            ),
        },
    ]
    if self.is_compositional_simplex:
        rows.append(
            {
                "dimension": "compositional_simplex",
                "signal": "compositional_simplex",
                "measured_value": (
                    f"simplex_total={self.simplex_total:.2f} | "
                    f"n_parts={self.n_series} | non_negative={self.non_negative}"
                ),
                "implication": (
                    "Constant-sum compositional simplex detected; routes Aitchison "
                    "log-ratio transforms (@transform_ilr / @transform_clr) with "
                    f"features.simplex_sum={self.simplex_total:.2f}."
                ),
            }
        )
    return pd.DataFrame(
        rows,
        columns=["dimension", "signal", "measured_value", "implication"],
    )

to_dict

to_dict()

Serialize profile to a plain JSON-compatible dictionary.

Source code in src/scale_forecasting/auto_policy.py
def to_dict(self) -> dict[str, Any]:
    """Serialize profile to a plain JSON-compatible dictionary."""
    raw = asdict(self)
    for k, v in list(raw.items()):
        if isinstance(v, tuple):
            raw[k] = list(v)
    raw["scale_regime"] = self.scale_regime
    return raw

PractitionerAssessmentFrame

Bases: DataFrame

DataFrame subclass for the 7-Question Practitioner Assessment that also supports substring checks against its formatted report text.

auto_forecast

auto_forecast(
    data,
    *,
    tier="wide_field",
    where="auto",
    goal="accuracy",
    allowed_families=None,
    base_config=None,
    overrides=None,
    models=None,
    include_models=None,
    exclude_models=None,
    baselines="auto",
    holidays=None,
    decision_metric=None,
    n_folds=None,
    hpo=None,
    ensemble=None,
    explainability=True,
    calibration=None,
    autofocus=True,
    autofocus_mode="dag",
    max_passes=None,
    max_autofocus_passes=None,
    max_minutes=None,
    max_wall_clock_minutes=None,
    max_usd=None,
    min_confidence=0.35,
    step_by_step=False,
    execute=True,
    future_df=None,
    ts_id_col=None,
    date_col=None,
    target_col=None,
    freq=None,
    horizon=None,
    run_name=None,
    settings=None,
)

Execute the Glass-Box Auto-Forecaster with optional closed-loop autofocus refinement.

  1. Plan (build_config): Profiles data, compiles the initial :class:ConfigBlueprint for tier while honoring user constraint pins, and verifies the wall-clock/cost budget.
  2. Execute Pass 1: Runs the initial model portfolio (locally in-memory when data is a pd.DataFrame and where in ('auto', 'local'), or on Google Cloud / BigQuery).
  3. Observe -> Review -> Re-Plan (autofocus=True): Audits FVA, Diebold–Mariano $p$-values, feature attributions, horizon decay crossover $h^*$, and residual heteroskedasticity/ACF. When autofocus_mode="dag" and multiple orthogonal hypotheses trigger, executes parallel Level-2 hypothesis branches (2A, 2B, 2C) while borrowing Pass 1's unchanged cells, followed by Level-3 synthesis and learned stacking backed by the Champion Ratchet.
Source code in src/scale_forecasting/auto.py
def auto_forecast(
    data: pd.DataFrame | str,
    *,
    tier: str = "wide_field",
    where: str = "auto",
    goal: str = "accuracy",
    allowed_families: Sequence[str] | None = None,
    base_config: RunConfig | Mapping[str, Any] | str | Path | None = None,
    overrides: Mapping[str, Any] | None = None,
    models: Sequence[str] | None = None,
    include_models: Sequence[str] | None = None,
    exclude_models: Sequence[str] | None = None,
    baselines: str | Sequence[str] | None = "auto",
    holidays: Sequence[str] | str | None = None,
    decision_metric: str | None = None,
    n_folds: int | None = None,
    hpo: bool | Mapping[str, Any] | None = None,
    ensemble: bool | Sequence[str] | Mapping[str, Any] | None = None,
    explainability: bool = True,
    calibration: DurationCalibration | bool | None = None,
    autofocus: bool = True,
    autofocus_mode: str = "dag",
    max_passes: int | None = None,
    max_autofocus_passes: int | None = None,
    max_minutes: float | None = None,
    max_wall_clock_minutes: float | None = None,
    max_usd: float | None = None,
    min_confidence: float = 0.35,
    step_by_step: bool = False,
    execute: bool = True,
    future_df: pd.DataFrame | None = None,
    ts_id_col: str | None = None,
    date_col: str | None = None,
    target_col: str | None = None,
    freq: str | None = None,
    horizon: int | None = None,
    run_name: str | None = None,
    settings: Settings | None = None,
) -> Forecaster:
    """Execute the Glass-Box Auto-Forecaster with optional closed-loop `autofocus` refinement.

    1. **Plan (`build_config`):** Profiles ``data``, compiles the initial :class:`ConfigBlueprint`
       for ``tier`` while honoring user constraint pins, and verifies the wall-clock/cost budget.
    2. **Execute Pass 1:** Runs the initial model portfolio (locally in-memory when ``data`` is a
       ``pd.DataFrame`` and ``where in ('auto', 'local')``, or on Google Cloud / BigQuery).
    3. **Observe -> Review -> Re-Plan (`autofocus=True`):** Audits FVA, Diebold–Mariano $p$-values,
       feature attributions, horizon decay crossover $h^*$, and residual heteroskedasticity/ACF.
       When ``autofocus_mode="dag"`` and multiple orthogonal hypotheses trigger, executes parallel
       Level-2 hypothesis branches (`2A`, `2B`, `2C`) while borrowing Pass 1's unchanged cells,
       followed by Level-3 synthesis and learned stacking backed by the Champion Ratchet.
    """
    tier = _normalize_tier(tier)
    if autofocus_mode not in ("dag", "linear"):
        raise ConfigError(
            f"Unknown autofocus_mode='{autofocus_mode}'. Valid values: 'dag', 'linear'"
        )
    if max_minutes is None and max_wall_clock_minutes is not None:
        max_minutes = max_wall_clock_minutes
    if max_passes is None and max_autofocus_passes is not None:
        max_passes = int(max_autofocus_passes) + 1

    blueprint = build_config(
        data,
        tier=tier,
        where=where,
        goal=goal,
        allowed_families=allowed_families,
        base_config=base_config,
        overrides=overrides,
        models=models,
        include_models=include_models,
        exclude_models=exclude_models,
        baselines=baselines,
        holidays=holidays,
        decision_metric=decision_metric,
        n_folds=n_folds,
        hpo=hpo,
        ensemble=ensemble,
        explainability=explainability,
        calibration=calibration,
        max_minutes=max_minutes,
        max_usd=max_usd,
        future_df=future_df,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        freq=freq,
        horizon=horizon,
        run_name=run_name,
        settings=settings,
    )

    tier_default_passes = int(EXPOSURE_TIERS[tier]["default_max_passes"])
    eff_max_passes = (
        1
        if not autofocus
        else int(max_passes if max_passes is not None else max(2, tier_default_passes))
    )

    session = AutoForecastSession(
        blueprint=blueprint,
        profile=blueprint.profile,
        tier=tier,
        where=blueprint.where,
        goal=goal,
        max_minutes=max_minutes,
        max_usd=max_usd,
        min_confidence=min_confidence,
        max_passes=eff_max_passes,
        autofocus_mode=autofocus_mode,
        exclude_models=tuple(exclude_models or ()),
        pinned_models=(models is not None),
        pinned_hpo=(hpo if isinstance(hpo, bool) else None),
        baselines=blueprint.baselines,
        data_df=data.copy() if isinstance(data, pd.DataFrame) else None,
        future_df=future_df.copy() if future_df is not None else None,
    )

    if not execute:
        from .sdk import Forecaster

        f_dry = Forecaster(blueprint.config, settings=settings)
        f_dry._auto_session = session
        return f_dry

    forecaster = execute_one_session_pass(
        session,
        blueprint.config,
        pass_index=1,
        mutations_applied=("initial_tier_compilation",),
        pass_id="1",
        parent_pass_ids=(),
        branch_hypothesis="Initial Tier Exposure",
        settings=settings,
    )

    if not autofocus or step_by_step or eff_max_passes <= 1:
        return forecaster

    pass1_record = session.passes[0]
    pass1_dict = pass1_record.config.model_dump(mode="json")
    pass1_diag = dict(session.last_diagnostics_summary)

    # Multi-branch Tournament DAG mode when multiple orthogonal hypotheses trigger on Pass 1
    preview1 = build_next_loop_preview(session)
    if not preview1.should_continue:
        return forecaster

    if autofocus_mode == "dag" and len(preview1.branches) >= 2:
        branch_outcomes: list[dict[str, Any]] = []
        for b_spec in preview1.branches:
            elapsed_m = sum(p.actual_wall_s for p in session.passes) / 60.0
            if max_minutes is not None and elapsed_m >= max_minutes:
                break
            b_id = str(b_spec.get("pass_id", "2A"))
            b_cfg = _compile_proposal_into_config(
                session,
                pass1_dict,
                b_spec,
                run_suffix=f"p{b_id.lower()}",
                prior_run_id=pass1_record.run_id,
            )
            b_muts = list(b_spec.get("mutations", []))
            b_actions = tuple(m.get("action", "refine") for m in b_muts) or ("refine",)
            # Restore Pass 1 diagnostics before evaluating each parallel branch
            session.last_diagnostics_summary = dict(pass1_diag)
            forecaster = execute_one_session_pass(
                session,
                b_cfg,
                pass_index=2,
                mutations_applied=b_actions,
                pass_id=b_id,
                parent_pass_ids=("1",),
                branch_hypothesis=str(b_spec.get("branch_hypothesis", "Hypothesis Branch")),
                mutations_detail=b_muts,
                settings=settings,
            )
            rec_b = session.passes[-1]
            branch_outcomes.append(
                {
                    "pass_id": b_id,
                    "config_dict": b_cfg.model_dump(mode="json"),
                    "best_score": rec_b.champion_score,
                    "pass1_score": pass1_record.champion_score,
                    "best_model": rec_b.champion_model,
                    "mutations_applied": b_actions,
                }
            )

        # Level 3 Synthesis & Stacking Join Node (when eff_max_passes >= 3 or >=2 branches win)
        winning_branches = [
            b for b in branch_outcomes if b["best_score"] <= b["pass1_score"] * 1.005
        ]
        elapsed_m = sum(p.actual_wall_s for p in session.passes) / 60.0
        can_run_synth = (
            len(branch_outcomes) >= 2
            and (eff_max_passes >= 3 or len(winning_branches) >= 2)
            and (max_minutes is None or elapsed_m < max_minutes)
        )
        if can_run_synth:
            synth_spec = propose_autofocus_synthesis_pass(
                session.profile,
                pass1_dict,
                branch_outcomes,
                tier=session.tier,
                where=session.where,
                goal=session.goal,
            )
            synth_cfg = _compile_proposal_into_config(
                session,
                pass1_dict,
                synth_spec,
                run_suffix="p3-synth",
                prior_run_id=session.run_id,
            )
            synth_muts = list(synth_spec.get("mutations", []))
            forecaster = execute_one_session_pass(
                session,
                synth_cfg,
                pass_index=3,
                mutations_applied=("synthesize_winning_dag_branches",),
                pass_id="3",
                parent_pass_ids=tuple(synth_spec.get("parent_pass_ids", ("2A", "2B"))),
                branch_hypothesis=str(
                    synth_spec.get(
                        "branch_hypothesis", "Level-3 Tournament Synthesis & Learned Stacking"
                    )
                ),
                mutations_detail=synth_muts,
                settings=settings,
            )
        return forecaster

    # Linear / Single-Branch loop
    while len(session.passes) < eff_max_passes:
        preview = build_next_loop_preview(session)
        if not preview.should_continue:
            break
        mut_records = preview.mutations_df.to_dict(orient="records")
        mut_names = tuple(str(r["action"]) for r in mut_records) if mut_records else ("refine",)
        b_title = (
            str(preview.branches[0].get("branch_hypothesis", ", ".join(mut_names)))
            if preview.branches
            else ", ".join(mut_names)
        )
        forecaster = execute_one_session_pass(
            session,
            preview.proposed_config,
            pass_index=preview.next_pass_index,
            mutations_applied=mut_names,
            pass_id=str(preview.next_pass_index),
            parent_pass_ids=(session.passes[-1].pass_id,),
            branch_hypothesis=b_title,
            mutations_detail=[{str(k): str(v) for k, v in r.items()} for r in mut_records],
            settings=settings,
        )

    return forecaster

build_config

build_config(
    data,
    *,
    tier="wide_field",
    where="auto",
    goal="accuracy",
    allowed_families=None,
    base_config=None,
    overrides=None,
    models=None,
    include_models=None,
    exclude_models=None,
    baselines="auto",
    holidays=None,
    decision_metric=None,
    n_folds=None,
    hpo=None,
    ensemble=None,
    explainability=True,
    calibration=None,
    max_minutes=None,
    max_wall_clock_minutes=None,
    max_usd=None,
    only_available_models=True,
    future_df=None,
    ts_id_col=None,
    date_col=None,
    target_col=None,
    freq=None,
    horizon=None,
    run_name=None,
    settings=None,
)

Compile a Glass-Box :class:ConfigBlueprint (RunConfig + Rationale Table + Duration).

100% transparent compiler: inspects data (or accepts an already-computed :class:PanelAutoProfile), applies the evolved decision policy in :mod:auto_policy, layers any explicit user constraint pins (base_config, overrides, models, include_models, exclude_models, baselines, holidays, decision_metric, n_folds, hpo, ensemble, explainability), enforces max_minutes and max_usd budgets via :func:predict_run_duration, and returns a validated :class:ConfigBlueprint.

Source code in src/scale_forecasting/auto.py
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
def build_config(
    data: pd.DataFrame | str | PanelAutoProfile,
    *,
    tier: str = "wide_field",
    where: str = "auto",
    goal: str = "accuracy",
    allowed_families: Sequence[str] | None = None,
    base_config: RunConfig | Mapping[str, Any] | str | Path | None = None,
    overrides: Mapping[str, Any] | None = None,
    models: Sequence[str] | None = None,
    include_models: Sequence[str] | None = None,
    exclude_models: Sequence[str] | None = None,
    baselines: str | Sequence[str] | None = "auto",
    holidays: Sequence[str] | str | None = None,
    decision_metric: str | None = None,
    n_folds: int | None = None,
    hpo: bool | Mapping[str, Any] | None = None,
    ensemble: bool | Sequence[str] | Mapping[str, Any] | None = None,
    explainability: bool = True,
    calibration: DurationCalibration | bool | None = None,
    max_minutes: float | None = None,
    max_wall_clock_minutes: float | None = None,
    max_usd: float | None = None,
    only_available_models: bool = True,
    future_df: pd.DataFrame | None = None,
    ts_id_col: str | None = None,
    date_col: str | None = None,
    target_col: str | None = None,
    freq: str | None = None,
    horizon: int | None = None,
    run_name: str | None = None,
    settings: Settings | None = None,
) -> ConfigBlueprint:
    """Compile a Glass-Box :class:`ConfigBlueprint` (`RunConfig` + Rationale Table + Duration).

    100% transparent compiler: inspects ``data`` (or accepts an already-computed
    :class:`PanelAutoProfile`), applies the evolved decision policy in :mod:`auto_policy`,
    layers any explicit user constraint pins (`base_config`, `overrides`, `models`,
    `include_models`, `exclude_models`, `baselines`, `holidays`, `decision_metric`, `n_folds`,
    `hpo`, `ensemble`, `explainability`), enforces ``max_minutes`` and ``max_usd`` budgets via
    :func:`predict_run_duration`, and returns a validated :class:`ConfigBlueprint`.
    """
    tier = _normalize_tier(tier)
    if max_minutes is None and max_wall_clock_minutes is not None:
        max_minutes = max_wall_clock_minutes
    if where not in ("auto", "local", "bigquery", "cloud_cpu", "cloud_all"):
        raise ConfigError(
            f"Unknown where='{where}'. Valid values: "
            "'auto', 'local', 'bigquery', 'cloud_cpu', 'cloud_all'"
        )
    if goal not in ("accuracy", "probabilistic", "service_level", "fast"):
        raise ConfigError(
            f"Unknown goal='{goal}'. Valid values: "
            "'accuracy', 'probabilistic', 'service_level', 'fast'"
        )

    base_seed = _extract_base_config_overrides(base_config)
    seed_data = (
        dict(base_seed.get("data", {})) if isinstance(base_seed.get("data"), Mapping) else {}
    )

    if isinstance(data, PanelAutoProfile):
        profile = data
        if horizon is not None and horizon != profile.horizon:
            profile = replace(profile, horizon=int(horizon))
    else:
        profile = inspect_panel_for_auto(
            data,
            future_df=future_df,
            ts_id_col=ts_id_col or seed_data.get("ts_id_col"),
            date_col=date_col or seed_data.get("date_col"),
            target_col=target_col or seed_data.get("target_col"),
            freq=freq or seed_data.get("freq"),
            horizon=horizon or seed_data.get("horizon"),
            settings=settings,
        )

    eff_where = (
        "local" if (where == "auto" and profile.source_table == "dataframe_panel") else where
    )
    avail_models = _available_models_for_where(
        "local" if only_available_models and eff_where == "local" else eff_where,
        exclude_models=exclude_models,
    )

    policy_out = select_tier_models_and_features(
        profile,
        tier=tier,
        where=eff_where,
        goal=goal,
        allowed_families=allowed_families,
        available_models=avail_models,
    )

    selected_models: list[str] = list(policy_out["models"])
    rationales: list[dict[str, str]] = list(policy_out["rationales"])
    protected_models: set[str] = {"naive_seasonal"}

    if allowed_families is not None:
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "allowed_families",
                "value": ", ".join(allowed_families),
                "evidence": "Explicit user pin [PINNED]",
                "rationale": "Restricts candidate model selection to user-approved families.",
            }
        )

    # Apply model pins / inclusions / exclusions
    if models is not None:
        selected_models = list(dict.fromkeys(str(m) for m in models))
        protected_models.update(selected_models)
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "models",
                "value": ", ".join(selected_models),
                "evidence": "Explicit user pin [PINNED]",
                "rationale": "Uses the exact model portfolio specified by the caller.",
            }
        )
    elif "models" in base_seed and isinstance(base_seed["models"], Sequence):
        selected_models = list(dict.fromkeys(str(m) for m in base_seed["models"]))
        protected_models.update(selected_models)
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "models",
                "value": ", ".join(selected_models),
                "evidence": "Seeded from base_config [PINNED]",
                "rationale": "Preserves the model list declared in base_config.",
            }
        )

    if exclude_models:
        excl_set = set(exclude_models)
        excl_bases = {m.split("@", 1)[0] for m in excl_set}
        selected_models = [
            m for m in selected_models if m not in excl_set and m.split("@", 1)[0] not in excl_bases
        ]
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "exclude_models",
                "value": ", ".join(exclude_models),
                "evidence": "Explicit user pin [PINNED]",
                "rationale": "Excludes user-disallowed models from Pass 1 and autofocus.",
            }
        )

    if include_models:
        for inc_m in include_models:
            if inc_m not in selected_models:
                selected_models.append(inc_m)
            protected_models.add(inc_m)
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "include_models",
                "value": ", ".join(include_models),
                "evidence": "Explicit user pin [PINNED]",
                "rationale": "Guarantees user-requested models are included and never trimmed.",
            }
        )

    # Resolve 4-anchor baseline ladder (or user-pinned baselines)
    baseline_entries = select_default_baselines(
        profile,
        where=eff_where,
        available_models=avail_models,
        selected_models=selected_models,
        user_baselines=baselines,
    )
    user_pinned_baselines = baselines is not None and baselines != "auto"
    for b_entry in baseline_entries:
        b_m = str(b_entry["model_type"])
        b_base = b_m.split("@", 1)[0]
        if user_pinned_baselines:
            if b_m not in selected_models and (b_base in avail_models or not only_available_models):
                selected_models.append(b_m)
            protected_models.add(b_m)
        elif b_entry["baseline_role"] in ("naive_anchor", "plain_univariate_stat"):
            protected_models.add(b_m)

    if baseline_entries:
        b_summary = ", ".join(f"{b['model_type']} ({b['baseline_role']})" for b in baseline_entries)
        rationales.append(
            {
                "category": "user_constraint" if user_pinned_baselines else "baseline_ladder",
                "parameter": "baselines",
                "value": b_summary,
                "evidence": (
                    f"baselines={baselines} [PINNED]"
                    if user_pinned_baselines
                    else (
                        "4-anchor baseline ladder (naive, plain univariate, "
                        "foundation, covariate ablation)"
                    )
                ),
                "rationale": (
                    "Guarantees protected baseline anchors across passes so every model and "
                    "mutation is scored on Forecast Value Added (FVA) over baseline."
                ),
            }
        )

    # Explainability guarantee: if explainability=True and ML family is allowed, ensure at least
    # one attribution-capable model is in the portfolio
    if (
        explainability
        and models is None
        and (allowed_families is None or "ml" in allowed_families)
        and eff_where != "bigquery"
    ):
        has_explainable = any(
            get_model(base_model_name(m)).supports_explainability for m in selected_models
        )
        if not has_explainable:
            for exp_cand in ("lightgbm", "regression_lags", "xgboost"):
                if exp_cand in avail_models:
                    selected_models.append(exp_cand)
                    rationales.append(
                        {
                            "category": "explainability",
                            "parameter": exp_cand,
                            "value": "include (explainability=True)",
                            "evidence": "supports_explainability=True",
                            "rationale": (
                                "Ensures Tier 1 global feature attributions and Tier 2 per-step "
                                "explanations are populated."
                            ),
                        }
                    )
                    break

    if not selected_models:
        selected_models = ["naive_seasonal", "theta"]

    hol_list: list[str] = list(policy_out.get("holidays", []))
    if holidays is not None:
        hol_list = [holidays] if isinstance(holidays, str) else [str(h) for h in holidays]
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "features.holidays",
                "value": ", ".join(hol_list),
                "evidence": "Explicit user pin [PINNED]",
                "rationale": "Enables country holiday calendar indicator features.",
            }
        )

    features_cfg: dict[str, Any] = {
        "future_covariates": list(profile.future_covariates),
        "past_covariates": list(profile.past_covariates),
        "static_covariates": list(profile.static_covariates),
        "transform": policy_out["target_transform"],
        "outlier_policy": policy_out["outlier_policy"],
        "level_shift": bool(policy_out["level_shift"]),
        "regime_routing": bool(policy_out["regime_routing"]),
        "fourier": bool(policy_out.get("fourier", False)),
        "trading_days": bool(policy_out.get("trading_days", False)),
        "holidays": hol_list,
        "include_univariate_baselines": (
            False if models is not None else bool(policy_out["include_univariate_baselines"])
        ),
        "ablation_modes": [] if models is not None else list(policy_out["ablation_modes"]),
    }
    if policy_out.get("simplex_sum") is not None:
        features_cfg["simplex_sum"] = float(policy_out["simplex_sum"])
    if policy_out.get("censored_col"):
        features_cfg["censored_col"] = policy_out["censored_col"]
    if policy_out.get("monotonic_constraints"):
        features_cfg["monotonic_constraints"] = dict(policy_out["monotonic_constraints"])
    if hol_list and str(profile.freq).strip().upper() in ("D", "B", "H", "1H", "BH"):
        features_cfg["holiday_window"] = {
            "enabled": True,
            "pre_holiday_days": 7,
            "post_holiday_days": 3,
            "kernel": "linear",
        }
        rationales.append(
            {
                "category": "features",
                "parameter": "features.holiday_window",
                "value": "pre=7d, post=3d, kernel='linear'",
                "evidence": f"holidays={hol_list}, freq='{profile.freq}'",
                "rationale": (
                    "Expands point-day holiday indicators into asymmetric pre-holiday stock-up "
                    "ramps and post-holiday dip windows."
                ),
            }
        )

    if profile.future_covariates:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.future_covariates",
                "value": ", ".join(profile.future_covariates),
                "evidence": f"{len(profile.future_covariates)} known future driver(s) detected",
                "rationale": "Registers known future drivers for elastic and global models.",
            }
        )
    if profile.static_covariates:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.static_covariates",
                "value": ", ".join(profile.static_covariates),
                "evidence": f"{len(profile.static_covariates)} time-invariant series attribute(s)",
                "rationale": "Enables cross-series conditioning on static metadata.",
            }
        )

    hierarchy_cfg: dict[str, Any] = {"enabled": False}
    has_bq_native_model = any(
        get_model(base_model_name(m)).runtime == "bigquery" for m in selected_models
    )
    if profile.hierarchy_id_cols and eff_where != "bigquery" and not has_bq_native_model:
        rec_methods = list(select_hierarchy_reconciliation_methods(profile, tier=tier))
        h_cols = list(profile.hierarchy_id_cols)
        h_levels = [h_cols[: i + 1] for i in range(len(h_cols))]
        hierarchy_cfg = {
            "enabled": True,
            "levels": h_levels,
            "reconciliation_methods": rec_methods,
        }
        rationales.append(
            {
                "category": "hierarchy",
                "parameter": "hierarchy.reconciliation_methods",
                "value": ", ".join(rec_methods),
                "evidence": (
                    f"hierarchy_id_cols={list(profile.hierarchy_id_cols)}, "
                    f"n_nodes={profile.hierarchy_node_count or profile.n_series}"
                ),
                "rationale": (
                    "Enforces additive cross-level coherence and scale-aware non-negative leaf "
                    f"reconciliation ({', '.join(rec_methods)})."
                ),
            }
        )

    output_cfg: dict[str, Any] = {
        "point_forecast": "auto" if goal in ("service_level", "probabilistic") else "raw",
        "quantiles": list(policy_out["quantiles"]),
        "integer_rounding": policy_out["integer_rounding"],
    }
    if policy_out.get("floor") is not None:
        output_cfg["floor"] = policy_out["floor"]
    if policy_out.get("target_quantile") is not None:
        output_cfg["target_quantile"] = policy_out["target_quantile"]
    if policy_out.get("underage_cost") is not None:
        output_cfg["underage_cost"] = policy_out["underage_cost"]
    if policy_out.get("overage_cost") is not None:
        output_cfg["overage_cost"] = policy_out["overage_cost"]

    if isinstance(calibration, bool):
        output_cfg["point_forecast"] = "auto" if calibration else "raw"
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "output.point_forecast",
                "value": output_cfg["point_forecast"],
                "evidence": f"calibration={calibration} [PINNED]",
                "rationale": "Applies user-pinned OOF point-forecast calibration policy.",
            }
        )
    elif isinstance(calibration, str) and calibration in ("raw", "median", "mean", "auto"):
        output_cfg["point_forecast"] = calibration
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "output.point_forecast",
                "value": calibration,
                "evidence": f"calibration='{calibration}' [PINNED]",
                "rationale": "Applies user-pinned OOF point-forecast calibration policy.",
            }
        )

    eff_n_folds = int(n_folds) if n_folds is not None else int(policy_out["n_folds"])
    if n_folds is not None:
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "backtest.n_folds",
                "value": str(eff_n_folds),
                "evidence": "Explicit user pin [PINNED]",
                "rationale": (
                    f"Pins rolling-origin backtest cross-validation to {eff_n_folds} fold(s)."
                ),
            }
        )

    eff_decision_metric = (
        _normalize_decision_metric(decision_metric)
        if decision_metric is not None
        else str(policy_out["decision_metric"])
    )
    if decision_metric is not None:
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "backtest.decision_metric",
                "value": eff_decision_metric,
                "evidence": "Explicit user pin [PINNED]",
                "rationale": (
                    f"Pins model ranking and ensemble optimization to '{eff_decision_metric}'."
                ),
            }
        )

    eff_min_obs = (
        int(profile.min_n_obs * 0.55) if policy_out.get("trim_leading_zeros") else profile.min_n_obs
    )
    min_train_obs = max(14, min(180, max(14, eff_min_obs - profile.horizon * eff_n_folds - 2)))
    backtest_cfg: dict[str, Any] = {
        "enabled": eff_n_folds >= 1,
        "n_folds": max(1, eff_n_folds),
        "horizon": profile.horizon,
        "step": profile.horizon,
        "min_train": min_train_obs,
        "decision_metric": eff_decision_metric,
    }
    if profile.min_n_obs < profile.horizon * (eff_n_folds + 1) + 5:
        backtest_cfg["short_series"] = "adapt"

    ensemble_strats = list(policy_out["ensemble_strategies"])
    sel_rule = policy_out.get("selection_rule")
    if sel_rule in ("champion", "horizon_specialist") and sel_rule not in ensemble_strats:
        ensemble_strats.append(sel_rule)
    ensemble_cfg: dict[str, Any] = {
        "enabled": len(selected_models) >= 2,
        "strategies": ensemble_strats,
        "parsimony_margin": float(policy_out.get("parsimony_margin", 0.005)),
    }
    if policy_out.get("ensemble_top_k") is not None:
        ensemble_cfg["top_k"] = int(policy_out["ensemble_top_k"])
    if ensemble is not None:
        if isinstance(ensemble, bool):
            ensemble_cfg["enabled"] = ensemble and len(selected_models) >= 2
        elif isinstance(ensemble, Sequence) and not isinstance(ensemble, str):
            ensemble_cfg["enabled"] = len(ensemble) > 0 and len(selected_models) >= 2
            ensemble_cfg["strategies"] = [str(s) for s in ensemble]
        elif isinstance(ensemble, Mapping):
            ensemble_cfg = _deep_merge_dict(ensemble_cfg, ensemble)
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "ensemble",
                "value": str(ensemble_cfg),
                "evidence": "Explicit user pin [PINNED]",
                "rationale": "Applies user-pinned ensemble strategy configuration.",
            }
        )

    hpo_cfg: dict[str, Any] = {
        "enabled": bool(policy_out["hpo_enabled"]),
        "n_trials": int(policy_out["hpo_trials"]) if policy_out["hpo_enabled"] else 10,
        "granularity": str(policy_out.get("hpo_granularity", "fleetwide")),
    }
    if hpo is not None:
        if isinstance(hpo, bool):
            hpo_cfg["enabled"] = hpo
            if hpo and int(hpo_cfg.get("n_trials", 0)) < 5:
                hpo_cfg["n_trials"] = 8
        elif isinstance(hpo, Mapping):
            hpo_cfg = _deep_merge_dict(hpo_cfg, hpo)
        rationales.append(
            {
                "category": "user_constraint",
                "parameter": "hpo",
                "value": f"enabled={hpo_cfg['enabled']}, n_trials={hpo_cfg.get('n_trials')}",
                "evidence": "Explicit user pin [PINNED]",
                "rationale": "Applies user-pinned Optuna hyperparameter optimization setting.",
            }
        )

    slug_tier = tier.replace("_", "-")
    data_cfg: dict[str, Any] = {
        "source_table": profile.source_table,
        "ts_id_col": profile.ts_id_col,
        "date_col": profile.date_col,
        "target_col": profile.target_col,
        "freq": profile.freq,
        "horizon": profile.horizon,
        "trim_leading_zeros": bool(policy_out.get("trim_leading_zeros", False)),
        "grid_policy": str(policy_out.get("grid_policy", "strict")),
    }
    raw_cfg: dict[str, Any] = {
        "run_name": run_name or base_seed.get("run_name") or f"auto-{slug_tier}",
        "data": data_cfg,
        "models": selected_models,
        "model_params": dict(policy_out.get("model_params", {})),
        "features": features_cfg,
        "backtest": backtest_cfg,
        "output": output_cfg,
        "hpo": hpo_cfg,
        "ensemble": ensemble_cfg,
        "hierarchy": hierarchy_cfg,
        "compute": _build_compute_block_for_where(
            eff_where,
            selected_models,
            n_series=profile.n_series,
            max_usd=max_usd,
        ),
    }

    # Merge any remaining sub-blocks from base_config (unless overridden by explicit pins)
    for block_key in (
        "features",
        "backtest",
        "output",
        "hpo",
        "ensemble",
        "hierarchy",
        "compute",
        "model_params",
    ):
        if block_key in base_seed and isinstance(base_seed[block_key], Mapping):
            # Explicit keyword arguments take precedence over base_seed
            if block_key == "hpo" and hpo is not None:
                continue
            if block_key == "ensemble" and ensemble is not None:
                continue
            merged_blk = _deep_merge_dict(dict(raw_cfg.get(block_key, {})), base_seed[block_key])
            if block_key == "backtest":
                if decision_metric is not None:
                    merged_blk["decision_metric"] = eff_decision_metric
                if n_folds is not None:
                    merged_blk["n_folds"] = max(1, eff_n_folds)
            raw_cfg[block_key] = merged_blk

    # Apply explicit dictionary overrides last (highest priority)
    if overrides:
        raw_cfg = _deep_merge_dict(raw_cfg, overrides)
        selected_models = list(raw_cfg.get("models", selected_models))
        for ov_k, ov_v in overrides.items():
            rationales.append(
                {
                    "category": "user_constraint",
                    "parameter": f"overrides.{ov_k}",
                    "value": str(ov_v),
                    "evidence": "Explicit user override [PINNED]",
                    "rationale": f"Applied explicit dictionary override on '{ov_k}'.",
                }
            )

    # Filter out covariates that don't exist in the current panel when base_config is supplied
    if not any(k in (overrides or {}) for k in ("features",)) and "features" in base_seed:
        valid_covs = (
            set(profile.future_covariates)
            | set(profile.past_covariates)
            | set(profile.static_covariates)
        )
        for cov_field in ("future_covariates", "past_covariates", "static_covariates", "exog"):
            if cov_field in raw_cfg["features"]:
                raw_cfg["features"][cov_field] = [
                    c for c in raw_cfg["features"][cov_field] if c in valid_covs
                ]

    # Resolve optional live duration calibration
    eff_calibration: DurationCalibration | None = None
    if isinstance(calibration, DurationCalibration):
        eff_calibration = calibration
    elif calibration is True:
        with contextlib.suppress(Exception):
            eff_calibration = calibrate_duration_from_registry(settings=settings)

    cfg = RunConfig.model_validate(raw_cfg)
    dur = predict_run_duration(
        cfg,
        n_series=profile.n_series,
        median_n_obs=float(profile.median_n_obs),
        where="local" if eff_where == "local" else None,
        calibration=eff_calibration,
    )

    # Budget clamping: if max_minutes or max_usd is exceeded, trim heaviest non-protected models
    while len(selected_models) > 2 and (
        (max_minutes is not None and dur.total_p50_minutes > max_minutes)
        or (max_usd is not None and dur.estimated_usd > max_usd)
    ):
        trim_idx = next(
            (
                i
                for i in range(len(selected_models) - 1, -1, -1)
                if selected_models[i] not in protected_models
            ),
            None,
        )
        if trim_idx is None:
            break
        dropped = selected_models.pop(trim_idx)
        raw_cfg["models"] = list(selected_models)
        if hpo is None:
            raw_cfg["hpo"] = {"enabled": False, "n_trials": 5, "granularity": "fleetwide"}
        cfg = RunConfig.model_validate(raw_cfg)
        dur = predict_run_duration(
            cfg,
            n_series=profile.n_series,
            median_n_obs=float(profile.median_n_obs),
            where="local" if eff_where == "local" else None,
            calibration=eff_calibration,
        )
        rationales.append(
            {
                "category": "budget_guardrail",
                "parameter": dropped,
                "value": "trimmed",
                "evidence": f"max_minutes={max_minutes}, max_usd={max_usd}",
                "rationale": (
                    f"Trimmed '{dropped}' (and disabled HPO) so predicted duration "
                    f"({dur.total_p50_minutes:.2f}m, ${dur.estimated_usd:.2f}) stays within budget."
                ),
            }
        )

    rationale_df = pd.DataFrame(
        rationales,
        columns=["category", "parameter", "value", "evidence", "rationale"],
    )
    return ConfigBlueprint(
        config=cfg,
        profile=profile,
        tier=tier,
        where=eff_where,
        goal=goal,
        rationale_df=rationale_df,
        duration_estimate=dur,
        cost_estimate_usd=dur.estimated_usd,
        baselines=tuple(baseline_entries),
    )

build_next_loop_preview

build_next_loop_preview(session)

Compute a :class:NextLoopPreview from the latest pass in session (pure).

Source code in src/scale_forecasting/auto.py
def build_next_loop_preview(session: AutoForecastSession) -> NextLoopPreview:
    """Compute a :class:`NextLoopPreview` from the latest pass in ``session`` (pure)."""
    last_pass = session.passes[-1]
    next_idx = last_pass.pass_index + 1
    prior_dict = last_pass.config.model_dump(mode="json")
    avail_models = _available_models_for_where(session.where, exclude_models=session.exclude_models)

    if session.autofocus_mode == "dag" and last_pass.pass_index == 1:
        branches = propose_autofocus_dag_branches(
            session.profile,
            prior_dict,
            next_idx,
            session.last_diagnostics_summary,
            tier=session.tier,
            where=session.where,
            goal=session.goal,
            available_models=avail_models,
        )
    else:
        branches = []

    proposal = propose_autofocus_pass(
        session.profile,
        prior_dict,
        next_idx,
        session.last_diagnostics_summary,
        tier=session.tier,
        where=session.where,
        goal=session.goal,
        available_models=avail_models,
    )

    mutations: list[dict[str, str]] = list(proposal["mutations"])
    next_cfg = _compile_proposal_into_config(
        session,
        prior_dict,
        proposal,
        run_suffix=f"p{next_idx}",
        prior_run_id=last_pass.run_id,
    )

    # Determine which models in next_cfg can be borrowed from Pass k vs must be fitted fresh
    prior_hashes = {make_model_spec_hash(m, last_pass.config): m for m in last_pass.config.models}
    borrowed: list[str] = []
    new_to_fit: list[str] = []
    for m in next_cfg.models:
        if make_model_spec_hash(m, next_cfg) in prior_hashes:
            borrowed.append(m)
        else:
            new_to_fit.append(m)

    dur = predict_run_duration(
        next_cfg,
        n_series=session.profile.n_series,
        median_n_obs=float(session.profile.median_n_obs),
        where="local" if session.where == "local" else None,
        borrowed_models=borrowed,
    )

    elapsed_minutes = sum(p.actual_wall_s for p in session.passes) / 60.0
    rem_minutes = (
        max(0.0, session.max_minutes - elapsed_minutes) if session.max_minutes is not None else None
    )

    conf_info = estimate_continue_confidence(
        session.profile,
        last_pass.pass_index,
        session.max_passes,
        session.last_diagnostics_summary,
        mutations,
        remaining_minutes=rem_minutes,
        next_pass_p50_minutes=dur.total_p50_minutes,
        min_confidence=session.min_confidence,
    )

    mutations_df = pd.DataFrame(
        mutations,
        columns=["action", "parameter", "old_value", "new_value", "evidence", "rationale"],
    )
    return NextLoopPreview(
        next_pass_index=next_idx,
        should_continue=bool(conf_info["should_continue"]),
        confidence=float(conf_info["confidence"]),
        expected_gain_pct=float(conf_info["expected_gain_pct"]),
        reason=str(conf_info["reason"]),
        proposed_config=next_cfg,
        mutations_df=mutations_df,
        borrowed_models=tuple(borrowed),
        new_models_to_fit=tuple(new_to_fit),
        duration_estimate=dur,
        branches=tuple(branches),
    )

execute_one_session_pass

execute_one_session_pass(
    session,
    cfg,
    pass_index,
    mutations_applied,
    *,
    pass_id=None,
    parent_pass_ids=None,
    branch_hypothesis=None,
    mutations_detail=None,
    settings=None,
)

Execute one pass (where == 'local' or cloud Forecaster.run), record it on session.

Source code in src/scale_forecasting/auto.py
def execute_one_session_pass(
    session: AutoForecastSession,
    cfg: RunConfig,
    pass_index: int,
    mutations_applied: tuple[str, ...],
    *,
    pass_id: str | None = None,
    parent_pass_ids: tuple[str, ...] | None = None,
    branch_hypothesis: str | None = None,
    mutations_detail: Sequence[dict[str, str]] | None = None,
    settings: Settings | None = None,
) -> Forecaster:
    """Execute one pass (`where == 'local'` or cloud `Forecaster.run`), record it on `session`."""
    from .sdk import Forecaster

    eff_pass_id = pass_id or str(pass_index)
    eff_parents = (
        parent_pass_ids
        if parent_pass_ids is not None
        else (() if pass_index == 1 else (str(pass_index - 1),))
    )
    eff_hypothesis = branch_hypothesis or (
        "Initial Tier Exposure" if pass_index == 1 else ", ".join(mutations_applied)
    )
    eff_mut_detail = tuple(mutations_detail or ())

    pred_dur = predict_run_duration(
        cfg,
        n_series=session.profile.n_series,
        median_n_obs=float(session.profile.median_n_obs),
        where="local" if session.where == "local" else None,
    )

    t0 = time.monotonic()
    if session.where == "local" and session.data_df is not None:
        full_panel = session.data_df.copy()

        out = _execute_local_panel_pass(
            full_panel,
            cfg,
            cell_cache=session.cell_cache,
            future_df=session.future_df,
        )
        wall_s = time.monotonic() - t0
        pass_outputs = {
            "leaderboard_df": out["leaderboard_df"],
            "predictions_df": out["predictions_df"],
            "raw_predictions_df": out["raw_predictions_df"],
            "oof_df": out["oof_df"],
            "fva_df": out["fva_df"],
            "horizon_decay_df": out["horizon_decay_df"],
            "bias_df": out["bias_df"],
            "attributions_df": out["attributions_df"],
            "hierarchy_summary_df": out["hierarchy_summary_df"],
            "hierarchy_spec": out.get("hierarchy_spec"),
            "diagnostics_summary": out["diagnostics_summary"],
        }
        session.last_diagnostics_summary = out["diagnostics_summary"]
        n_borrowed = len(out["borrowed_models"])
        n_executed = len(out["executed_models"])
        f = Forecaster(cfg, settings=settings)
    else:
        f = Forecaster(cfg, settings=settings)
        f.run()
        wall_s = time.monotonic() - t0
        lb_df = f.leaderboard_df()
        fva_df = f.fva_df()
        hd_df = f.horizon_decay_df()
        bias_df = f.bias_report_df()
        attr_df = f.attributions_df()
        from .registry.reads import read_oof

        oof_rows = read_oof(f.run_id, limit=20000, settings=settings)
        oof_df = pd.DataFrame.from_records(oof_rows) if oof_rows else pd.DataFrame()
        diag_cloud = _summarize_pass_diagnostics(
            cfg=cfg,
            leaderboard_df=lb_df,
            fva_df=fva_df,
            horizon_decay_df=hd_df,
            bias_df=bias_df,
            attributions_df=attr_df,
            oof_df=oof_df,
        )
        pass_outputs = {
            "leaderboard_df": lb_df,
            "predictions_df": pd.DataFrame(),
            "raw_predictions_df": pd.DataFrame(),
            "oof_df": oof_df,
            "fva_df": fva_df,
            "horizon_decay_df": hd_df,
            "bias_df": bias_df,
            "attributions_df": attr_df,
            "hierarchy_summary_df": pd.DataFrame(),
            "diagnostics_summary": diag_cloud,
        }
        session.last_diagnostics_summary = diag_cloud
        n_borrowed = 0 if pass_index == 1 else max(0, len(cfg.models) - len(mutations_applied))
        n_executed = max(1, len(cfg.models) - n_borrowed)

    diag = session.last_diagnostics_summary
    this_score = float(diag.get("best_score", float("nan")))

    # Champion Ratchet: update session active tables when this pass improves/ties champion
    if (
        not session.passes
        or not math.isfinite(session.champion_score)
        or (math.isfinite(this_score) and this_score <= session.champion_score)
    ):
        session.champion_pass_id = eff_pass_id
        session.champion_score = this_score
        session.champion_outputs = pass_outputs
        session.leaderboard_df = pass_outputs["leaderboard_df"]
        session.predictions_df = pass_outputs["predictions_df"]
        session.raw_predictions_df = pass_outputs["raw_predictions_df"]
        session.oof_df = pass_outputs["oof_df"]
        session.fva_df = pass_outputs["fva_df"]
        session.horizon_decay_df = pass_outputs["horizon_decay_df"]
        session.bias_df = pass_outputs["bias_df"]
        session.attributions_df = pass_outputs["attributions_df"]
        session.hierarchy_summary_df = pass_outputs["hierarchy_summary_df"]

    temp_record = AutofocusPassRecord(
        pass_index=pass_index,
        run_id=f.run_id,
        tier=session.tier,
        models_total=len(cfg.models),
        models_borrowed=n_borrowed,
        models_executed=n_executed,
        champion_model=str(diag.get("best_model", cfg.models[0])),
        decision_metric=str(diag.get("decision_metric", cfg.backtest.decision_metric)),
        champion_score=this_score,
        fva_vs_naive_pct=float(diag.get("fva_vs_naive_pct", 0.0)),
        dm_pvalue=diag.get("dm_pvalue"),
        predicted_p50_s=pred_dur.total_p50_s,
        actual_wall_s=wall_s,
        continue_confidence=0.0,
        expected_next_gain_pct=0.0,
        mutations_applied=mutations_applied,
        stop_or_continue_reason="",
        config=cfg,
        pass_id=eff_pass_id,
        parent_pass_ids=eff_parents,
        branch_hypothesis=eff_hypothesis,
        mutations_detail=eff_mut_detail,
        is_session_champion=False,
        fva_vs_univariate_pct=float(diag.get("fva_vs_univariate_pct", 0.0)),
        fva_vs_foundation_pct=float(diag.get("fva_vs_foundation_pct", 0.0)),
        covariate_lift_pct=float(diag.get("covariate_lift_pct", 0.0)),
        reconciliation_lift_pct=float(diag.get("reconciliation_lift_pct", 0.0)),
        champion_is_univariate=bool(diag.get("champion_is_univariate", False)),
        beaten_challengers=tuple(diag.get("beaten_challengers", ())),
    )
    session.passes.append(temp_record)
    preview = build_next_loop_preview(session)
    session.passes[-1] = replace(
        temp_record,
        continue_confidence=preview.confidence,
        expected_next_gain_pct=preview.expected_gain_pct,
        stop_or_continue_reason=preview.reason,
    )
    _refresh_session_champion_flags(session)

    # Ensure returned Forecaster carries the session champion config
    champ_rec = session.champion_record()
    if champ_rec is not None and champ_rec.config != f.config:
        f = Forecaster(champ_rec.config, settings=settings)
    f._auto_session = session
    return f

inspect_panel_for_auto

inspect_panel_for_auto(
    data,
    *,
    future_df=None,
    ts_id_col=None,
    date_col=None,
    target_col=None,
    freq=None,
    horizon=None,
    hierarchy_cols=None,
    settings=None,
)

Single-pass statistical & structural profiler for Glass-Box configuration compilation.

Inspects either an in-memory pd.DataFrame or a BigQuery source table name (str) and computes the :class:PanelAutoProfile driving model selection, covariate role classification, target transformations, SBC demand regime routing, and hierarchical reconciliation.

Source code in src/scale_forecasting/auto.py
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
def inspect_panel_for_auto(
    data: pd.DataFrame | str,
    *,
    future_df: pd.DataFrame | None = None,
    ts_id_col: str | None = None,
    date_col: str | None = None,
    target_col: str | None = None,
    freq: str | None = None,
    horizon: int | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    settings: Settings | None = None,
) -> PanelAutoProfile:
    """Single-pass statistical & structural profiler for Glass-Box configuration compilation.

    Inspects either an in-memory ``pd.DataFrame`` or a BigQuery source table name (`str`) and
    computes the :class:`PanelAutoProfile` driving model selection, covariate role classification,
    target transformations, SBC demand regime routing, and hierarchical reconciliation.
    """
    source_table_name = "dataframe_panel"
    true_total_series: int | None = None
    true_total_rows: int | None = None
    if isinstance(data, str):
        from .errors import require_extra
        from .registry.tables import bigquery_client
        from .settings import Settings

        require_extra("gcp", purpose="Inspecting a BigQuery source table for auto-forecasting")
        source_table_name = data
        eff_settings = settings or Settings.resolve()
        client = bigquery_client(eff_settings.project_id, location=eff_settings.region)
        fq_table = (
            data if "." in data else f"{eff_settings.project_id}.{eff_settings.dataset_id}.{data}"
        )
        id_col_guess, date_col_guess, target_col_guess = _resolve_bq_table_columns(
            client,
            fq_table,
            ts_id_col=ts_id_col,
            date_col=date_col,
            target_col=target_col,
        )
        ts_id_col = ts_id_col or id_col_guess
        date_col = date_col or date_col_guess
        target_col = target_col or target_col_guess
        sql = f"""
        WITH table_stats AS (
          SELECT COUNT(DISTINCT `{id_col_guess}`) AS _sf_total_series, COUNT(*) AS _sf_total_rows
          FROM `{fq_table}`
        ),
        sampled_ids AS (
          SELECT DISTINCT `{id_col_guess}`
          FROM `{fq_table}`
          LIMIT 150
        )
        SELECT t.*, s_tot._sf_total_series, s_tot._sf_total_rows
        FROM `{fq_table}` t
        JOIN sampled_ids s USING (`{id_col_guess}`)
        CROSS JOIN table_stats s_tot
        ORDER BY t.`{id_col_guess}`, t.`{date_col_guess}`
        """
        df = client.query(sql).to_dataframe()
        if "_sf_total_series" in df.columns:
            if not df.empty and pd.notna(df["_sf_total_series"].iloc[0]):
                true_total_series = int(df["_sf_total_series"].iloc[0])
            df = df.drop(columns=["_sf_total_series"])
        if "_sf_total_rows" in df.columns:
            if not df.empty and pd.notna(df["_sf_total_rows"].iloc[0]):
                true_total_rows = int(df["_sf_total_rows"].iloc[0])
            df = df.drop(columns=["_sf_total_rows"])
    else:
        df = data.copy()

    eff_ts, eff_date, eff_target, eff_freq = _infer_columns_and_freq(
        df,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        freq=freq,
    )
    eff_horizon = int(horizon or _DEFAULT_HORIZON_BY_FREQ.get(eff_freq, 14))

    # Separate historical rows (where target is not NaN) from trailing future covariate rows
    df[eff_date] = pd.to_datetime(df[eff_date], errors="coerce")
    y_num = pd.to_numeric(df[eff_target], errors="coerce")
    hist_df = df[y_num.notna()].copy()
    trailing_fut_df = df[y_num.isna()].copy()
    if future_df is not None and not future_df.empty:
        trailing_fut_df = future_df.copy()

    if hist_df.empty:
        raise DataError(
            f"Panel target column '{eff_target}' contains no non-null numeric observations."
        )

    hist_df = hist_df.sort_values([eff_ts, eff_date], kind="stable")
    y_vals = pd.to_numeric(hist_df[eff_target], errors="coerce").dropna().to_numpy(dtype=np.float64)

    non_negative = bool(np.all(y_vals >= 0.0))
    integer_valued = bool(np.mean(np.isclose(y_vals, np.round(y_vals), atol=1e-6)) >= 0.99)
    zero_fraction = float(np.mean(y_vals == 0.0))

    # Per-series SBC regime & heteroskedasticity diagnostics
    s_period = max(2, seasonal_period(eff_freq))
    obs_counts: list[int] = []
    adis: list[float] = []
    cv2s: list[float] = []
    lv_corrs: list[float] = []
    growth_ratios: list[float] = []
    acfs: list[float] = []
    break_flags: list[bool] = []
    spike_flags: list[bool] = []
    leading_zero_flags: list[bool] = []
    gap_flags: list[bool] = []
    regime_counts: dict[str, int] = {
        "smooth": 0,
        "erratic": 0,
        "intermittent": 0,
        "lumpy": 0,
        "cold_start": 0,
    }

    cold_threshold = max(28, 2 * eff_horizon)
    for _, grp in hist_df.groupby(eff_ts, sort=False):
        arr = pd.to_numeric(grp[eff_target], errors="coerce").dropna().to_numpy(dtype=np.float64)
        n = len(arr)
        if n == 0:
            continue
        obs_counts.append(n)
        pos_mask = arr > 0.0
        n_pos = int(np.sum(pos_mask))
        adi = float(n / max(1, n_pos))
        adis.append(adi)
        if n_pos > 0:
            first_pos_idx = int(np.argmax(pos_mask))
            leading_zero_flags.append(first_pos_idx >= max(4, int(0.10 * n)))
        else:
            leading_zero_flags.append(False)

        ds_vals = (
            pd.to_datetime(grp[eff_date], errors="coerce").dropna().to_numpy(dtype="datetime64[s]")
        )
        if len(ds_vals) >= 4:
            ds_diffs = np.diff(ds_vals).astype(np.float64)
            med_step = float(np.median(ds_diffs))
            gap_flags.append(bool(med_step > 0.0 and np.max(ds_diffs) > 1.75 * med_step))
        else:
            gap_flags.append(False)

        if n_pos >= 2:
            pos_vals = arr[pos_mask]
            pos_mean = float(np.mean(pos_vals))
            pos_std = float(np.std(pos_vals, ddof=0))
            cv2 = float((pos_std / max(1e-9, pos_mean)) ** 2)
        else:
            cv2 = 0.0
        cv2s.append(cv2)

        if n < cold_threshold:
            regime_counts["cold_start"] += 1
        elif adi < 1.32 and cv2 < 0.49:
            regime_counts["smooth"] += 1
        elif adi < 1.32 and cv2 >= 0.49:
            regime_counts["erratic"] += 1
        elif adi >= 1.32 and cv2 < 0.49:
            regime_counts["intermittent"] += 1
        else:
            regime_counts["lumpy"] += 1

        # Windowed level vs volatility correlation (diagnoses log-normal / multiplicative DGP)
        if n >= 28:
            n_wins = min(8, n // 7)
            chunks = np.array_split(arr, n_wins)
            w_means = np.array([float(np.mean(c)) for c in chunks])
            w_stds = np.array([float(np.std(c, ddof=0)) for c in chunks])
            if np.std(w_means) > 1e-6 and np.std(w_stds) > 1e-6:
                corr = float(np.corrcoef(w_means, w_stds)[0, 1])
                if math.isfinite(corr):
                    lv_corrs.append(corr)
            q_len = max(7, n // 4)
            start_mean = max(1e-6, float(np.mean(np.abs(arr[:q_len]))))
            end_mean = float(np.mean(np.abs(arr[-q_len:])))
            growth_ratios.append(end_mean / start_mean)

        # Seasonal lag autocorrelation
        if n >= s_period + 5 and np.std(arr) > 1e-6:
            c0 = arr[:-s_period] - np.mean(arr[:-s_period])
            c1 = arr[s_period:] - np.mean(arr[s_period:])
            denom = float(np.linalg.norm(c0) * np.linalg.norm(c1))
            if denom > 1e-9:
                acfs.append(float(np.dot(c0, c1) / denom))

        # Structural break & isolated spike check
        if n >= 40:
            best_z = 0.0
            for frac in (0.45, 0.55, 0.65, 0.72):
                sp = int(frac * n)
                left, right = arr[:sp], arr[sp:]
                l_med, r_med = float(np.median(left)), float(np.median(right))
                mad = float(np.median(np.abs(np.diff(arr)))) * 1.4826 + 1e-6
                z_step = abs(r_med - l_med) / max(mad * 1.8, 0.15 * max(abs(l_med), 1.0))
                best_z = max(best_z, z_step)
            break_flags.append(best_z >= 2.2)

            med_series = pd.Series(arr).rolling(7, center=True, min_periods=1).median().to_numpy()
            resid = np.abs(arr - med_series)
            rob_mad = float(np.median(resid)) * 1.4826 + 1e-6
            spike_flags.append(
                bool(np.max(resid) > 6.5 * rob_mad and np.mean(resid > 5.0 * rob_mad) < 0.06)
            )

    sampled_n_series = max(1, len(obs_counts))
    n_series = max(sampled_n_series, true_total_series or sampled_n_series)
    regime_shares = {k: round(v / sampled_n_series, 4) for k, v in regime_counts.items()}
    dominant_regime = max(regime_shares.items(), key=lambda kv: kv[1])[0]

    # Classify extra columns into censored_col, hierarchy_id_cols, static, future, past covariates
    reserved = {eff_ts, eff_date, eff_target, "archetype"}
    extra_cols = [c for c in df.columns if c not in reserved]

    censored_col: str | None = None
    for c in extra_cols:
        clower = c.lower()
        if any(tok in clower for tok in ("stockout", "censored", "oos_flag", "out_of_stock")):
            censored_col = c
            break
    if censored_col:
        extra_cols = [c for c in extra_cols if c != censored_col]

    # Hierarchy detection
    resolved_hierarchy: list[str] = []
    if hierarchy_cols is not None:
        resolved_hierarchy = [c for c in hierarchy_cols if c in df.columns]
    else:
        for cand_pair in (("region", "store"), ("state", "store_id"), ("category", "subcategory")):
            if all(c in extra_cols for c in cand_pair):
                resolved_hierarchy = list(cand_pair)
                break
    for hc in resolved_hierarchy:
        if hc in extra_cols:
            extra_cols.remove(hc)

    hierarchy_node_count = 0
    if resolved_hierarchy:
        hierarchy_node_count = 1 + n_series
        for lvl_idx in range(len(resolved_hierarchy)):
            lvl_cols = resolved_hierarchy[: lvl_idx + 1]
            hierarchy_node_count += int(hist_df[lvl_cols].drop_duplicates().shape[0])

    # Cross-series correlation across up to 12 sampled series
    cross_series_corr = 0.0
    if n_series >= 2:
        sampled_ids = list(hist_df[eff_ts].drop_duplicates().iloc[:12])
        sub_piv = (
            hist_df[hist_df[eff_ts].isin(sampled_ids)]
            .pivot_table(index=eff_date, columns=eff_ts, values=eff_target, aggfunc="mean")
            .dropna(axis=0, how="any")
        )
        if sub_piv.shape[0] >= 8 and sub_piv.shape[1] >= 2:
            cmat = sub_piv.corr().to_numpy(dtype=np.float64)
            tri_idx = np.triu_indices(cmat.shape[0], k=1)
            pair_vals = np.abs(cmat[tri_idx])
            pair_vals = pair_vals[np.isfinite(pair_vals)]
            if pair_vals.size > 0:
                cross_series_corr = float(np.median(pair_vals))

    static_covs: list[str] = []
    future_covs: list[str] = []
    past_covs: list[str] = []

    for c in extra_cols:
        max_nunq = int(hist_df.groupby(eff_ts, sort=False)[c].nunique(dropna=True).max() or 0)
        is_num = pd.api.types.is_numeric_dtype(df[c])
        if max_nunq <= 1 and (
            not is_num
            or any(
                tok in c.lower()
                for tok in ("tier", "category", "segment", "cluster", "static", "format")
            )
        ):
            static_covs.append(c)
        elif is_num:
            if (
                not trailing_fut_df.empty
                and c in trailing_fut_df.columns
                and trailing_fut_df[c].notna().any()
            ) or trailing_fut_df.empty:
                future_covs.append(c)
            else:
                past_covs.append(c)

    # Compositional simplex detection (parts summing to ~1.0 or ~100.0 per date)
    is_compositional_simplex = False
    simplex_total = 0.0
    if sampled_n_series >= 2 and non_negative:
        date_grp = hist_df.groupby(eff_date, sort=False)[eff_target]
        date_counts = date_grp.count()
        date_sums = date_grp.sum()
        full_dates = date_sums[date_counts >= min(2, sampled_n_series)]
        if len(full_dates) >= 5:
            sums_arr = full_dates.to_numpy(dtype=np.float64)
            med_sum = float(np.median(sums_arr))
            max_val = float(np.max(y_vals)) if y_vals.size > 0 else 0.0
            for cand_total in (1.0, 100.0):
                tol = 0.03 * cand_total
                if (
                    abs(med_sum - cand_total) <= tol
                    and max_val <= cand_total + tol
                    and float(np.mean(np.abs(sums_arr - cand_total) <= tol)) >= 0.90
                ):
                    is_compositional_simplex = True
                    simplex_total = cand_total
                    break

    cold_start_donor_similarity = 0.0
    if regime_shares.get("cold_start", 0.0) > 0.0 and sampled_n_series >= 2:
        try:
            from .cold_start import build_cold_start_donor_pool, cold_start_transfer_df

            min_mat = max(14, 2 * eff_horizon)
            pool = build_cold_start_donor_pool(
                hist_df,
                ts_id_col=eff_ts,
                date_col=eff_date,
                target_col=eff_target,
                min_obs=min_mat,
                horizon=eff_horizon,
            )
            if pool.donors:
                cs_df = cold_start_transfer_df(
                    hist_df,
                    min_obs=min_mat,
                    top_k_donors=3,
                    ts_id_col=eff_ts,
                    date_col=eff_date,
                    target_col=eff_target,
                    horizon=eff_horizon,
                )
                if not cs_df.empty and "donor_similarity" in cs_df.columns:
                    cold_start_donor_similarity = round(float(cs_df["donor_similarity"].mean()), 4)
                else:
                    cold_start_donor_similarity = round(max(0.68, cross_series_corr), 4)
        except Exception:  # noqa: BLE001 - fallback when donor pool cannot be constructed
            cold_start_donor_similarity = round(max(0.65, cross_series_corr), 4)

    residual_drift_ks_stat = round(
        float(np.mean(break_flags)) * 0.45 if break_flags else 0.0,
        4,
    )

    mean_pairwise_similarity = round(max(0.0, float(cross_series_corr)), 4)
    optimal_similarity_clusters = 1
    similarity_silhouette_score = 0.0
    lead_lag_pairs_count = 0
    has_similarity_clusters = False
    dominant_cluster_archetype = "steady_baseline"
    if sampled_n_series >= 2 and not hist_df.empty:
        try:
            from .similarity import cluster_by_similarity_df, compute_similarity_matrix

            sim_ids = [str(s) for s in hist_df[eff_ts].drop_duplicates().iloc[:24]]
            sim_sub = hist_df[hist_df[eff_ts].astype(str).isin(sim_ids)]
            sim_res = compute_similarity_matrix(
                sim_sub,
                method="hybrid",
                ts_id_col=eff_ts,
                date_col=eff_date,
                target_col=eff_target,
                max_lag=min(3, max(1, eff_horizon // 2)),
                top_k=max(3, min(10, len(sim_ids) - 1)),
            )
            mean_pairwise_similarity = round(
                float(sim_res.diagnostics.get("mean_pairwise_similarity", cross_series_corr)), 4
            )
            if not sim_res.pairs_df.empty and "optimal_lag" in sim_res.pairs_df.columns:
                lead_lag_pairs_count = int(
                    (
                        (sim_res.pairs_df["optimal_lag"].abs() > 0)
                        & (sim_res.pairs_df["similarity_score"] >= 0.50)
                    ).sum()
                )
            cl_df = cluster_by_similarity_df(
                sim_sub,
                n_clusters="auto",
                method="hybrid",
                ts_id_col=eff_ts,
                date_col=eff_date,
                target_col=eff_target,
                similarity_result=sim_res,
            )
            if not cl_df.empty:
                optimal_similarity_clusters = int(
                    max(1, int(cl_df["similarity_cluster_id"].nunique()))
                )
                similarity_silhouette_score = round(float(cl_df["silhouette_score"].mean()), 4)
                if "cluster_archetype" in cl_df.columns:
                    dominant_cluster_archetype = str(cl_df["cluster_archetype"].mode().iloc[0])
            has_similarity_clusters = bool(
                optimal_similarity_clusters >= 2 and similarity_silhouette_score >= 0.25
            )
        except Exception as exc:  # noqa: BLE001 - fallback when similarity profiling encounters degenerate data
            _log.debug("Step 0 similarity profiling skipped: %s", exc, exc_info=True)

    return PanelAutoProfile(
        source_table=source_table_name,
        ts_id_col=eff_ts,
        date_col=eff_date,
        target_col=eff_target,
        freq=eff_freq,
        horizon=eff_horizon,
        n_series=n_series,
        n_rows=max(len(hist_df), true_total_rows or len(hist_df)),
        median_n_obs=int(np.median(obs_counts)) if obs_counts else 0,
        min_n_obs=int(np.min(obs_counts)) if obs_counts else 0,
        max_n_obs=int(np.max(obs_counts)) if obs_counts else 0,
        non_negative=non_negative,
        integer_valued=integer_valued,
        zero_fraction=round(zero_fraction, 4),
        median_adi=round(float(np.median(adis)) if adis else 1.0, 4),
        median_cv2=round(float(np.median(cv2s)) if cv2s else 0.0, 4),
        level_vol_corr=round(float(np.median(lv_corrs)) if lv_corrs else 0.0, 4),
        end_to_start_ratio=round(float(np.median(growth_ratios)) if growth_ratios else 1.0, 4),
        dominant_regime=dominant_regime,
        regime_shares=regime_shares,
        median_acf_season=round(float(np.median(acfs)) if acfs else 0.0, 4),
        structural_break_share=round(float(np.mean(break_flags)) if break_flags else 0.0, 4),
        outlier_spike_share=round(float(np.mean(spike_flags)) if spike_flags else 0.0, 4),
        future_covariates=tuple(future_covs),
        past_covariates=tuple(past_covs),
        static_covariates=tuple(static_covs),
        hierarchy_id_cols=tuple(resolved_hierarchy),
        censored_col=censored_col,
        leading_zero_share=round(
            float(np.mean(leading_zero_flags)) if leading_zero_flags else 0.0, 4
        ),
        missing_date_gap_share=round(float(np.mean(gap_flags)) if gap_flags else 0.0, 4),
        hierarchy_node_count=hierarchy_node_count,
        cross_series_corr=round(cross_series_corr, 4),
        monotonic_constraints=infer_monotonic_constraints([*future_covs, *past_covs]),
        is_compositional_simplex=is_compositional_simplex,
        simplex_total=simplex_total,
        cold_start_donor_similarity=cold_start_donor_similarity,
        residual_drift_ks_stat=residual_drift_ks_stat,
        mean_pairwise_similarity=mean_pairwise_similarity,
        optimal_similarity_clusters=optimal_similarity_clusters,
        similarity_silhouette_score=similarity_silhouette_score,
        lead_lag_pairs_count=lead_lag_pairs_count,
        has_similarity_clusters=has_similarity_clusters,
        dominant_cluster_archetype=dominant_cluster_archetype,
    )

auto_policy

Glass-Box Auto-Forecaster & autofocus Decision Policy (Evolutionary Policy Module).

Contains the pure-Python decision rules that map a :class:PanelAutoProfile, an Observational Astronomy Exposure Tier ("first_light", "wide_field", "deep_sky", "deep_field"), and post-pass econometric diagnostics into concrete :class:~scale_forecasting.config.RunConfig specifications, multi-branch Tournament DAG hypotheses, and closed-loop autofocus mutations.

Why a standalone pure-Python policy module?

  1. Zero Runtime LLM / API Dependency: Production callers of Forecaster.build_config() and Forecaster.auto() execute deterministic, auditable Python math in milliseconds with zero external network calls.
  2. Build-Time Evolutionary Calibration (AlphaEvolve Mode A): The core policy functions are wrapped in evolutionary block markers so the in-repo benchmark evaluator (benchmarks.py) and Google Cloud AlphaEvolve (discoveryengine v1alpha with gemini-3.8-flash + gemini-4-argon) can evolve and verify policy improvements against the 12 canonical Data-Generating Process (DGP) benchmark panels.

PanelAutoProfile dataclass

PanelAutoProfile(
    source_table,
    ts_id_col,
    date_col,
    target_col,
    freq,
    horizon,
    n_series,
    n_rows,
    median_n_obs,
    min_n_obs,
    max_n_obs,
    non_negative,
    integer_valued,
    zero_fraction,
    median_adi,
    median_cv2,
    level_vol_corr,
    end_to_start_ratio,
    dominant_regime,
    regime_shares=dict(),
    median_acf_season=0.0,
    structural_break_share=0.0,
    outlier_spike_share=0.0,
    future_covariates=(),
    past_covariates=(),
    static_covariates=(),
    hierarchy_id_cols=(),
    censored_col=None,
    leading_zero_share=0.0,
    missing_date_gap_share=0.0,
    hierarchy_node_count=0,
    cross_series_corr=0.0,
    monotonic_constraints=dict(),
    is_compositional_simplex=False,
    simplex_total=0.0,
    cold_start_donor_similarity=0.0,
    residual_drift_ks_stat=0.0,
    mean_pairwise_similarity=0.0,
    optimal_similarity_clusters=1,
    similarity_silhouette_score=0.0,
    lead_lag_pairs_count=0,
    has_similarity_clusters=False,
    dominant_cluster_archetype="steady_baseline",
)

Single-pass statistical and structural profile of a time-series panel (pure).

scale_regime property

scale_regime

Canonical series-count scale regime (micro .. hyperscale).

explain

explain()

Return a formatted text summary of the Step 0 Data Profile & Readiness table.

Source code in src/scale_forecasting/auto_policy.py
def explain(self) -> str:
    """Return a formatted text summary of the Step 0 Data Profile & Readiness table."""
    df = self.to_df()
    header = (
        f"Step 0 Data Profile : {self.source_table} | {self.n_series} series "
        f"({self.scale_regime}) | freq='{self.freq}' | H={self.horizon}"
    )
    return f"{header}\n\n{df.to_string(index=False)}"

from_df classmethod

from_df(data, **kwargs)

Profile an in-memory DataFrame or BigQuery table via :func:inspect_panel_for_auto.

Source code in src/scale_forecasting/auto_policy.py
@classmethod
def from_df(cls, data: Any, **kwargs: Any) -> PanelAutoProfile:
    """Profile an in-memory DataFrame or BigQuery table via :func:`inspect_panel_for_auto`."""
    from .auto import inspect_panel_for_auto

    return inspect_panel_for_auto(data, **kwargs)

to_df

to_df()

Return a 7-row Step 0 Data Profile & Readiness DataFrame for human review.

Source code in src/scale_forecasting/auto_policy.py
def to_df(self) -> Any:
    """Return a 7-row Step 0 Data Profile & Readiness ``DataFrame`` for human review."""
    import pandas as pd

    scale_info = SCALE_REGIMES.get(self.scale_regime, SCALE_REGIMES["small"])
    cold_share = float(self.regime_shares.get("cold_start", 0.0))
    cov_list = (
        list(self.future_covariates) + list(self.past_covariates) + list(self.static_covariates)
    )
    rows = [
        {
            "dimension": "scale_and_shape",
            "signal": "n_series · history · scale_regime · cross_series_corr · similarity",
            "measured_value": (
                f"{self.n_series} series ({self.scale_regime}) | "
                f"freq='{self.freq}' | median_T={self.median_n_obs} "
                f"(min={self.min_n_obs}, max={self.max_n_obs}) | H={self.horizon} | "
                f"corr={self.cross_series_corr:.2f} | "
                f"sim={self.mean_pairwise_similarity:.2f} "
                f"(K={self.optimal_similarity_clusters}, "
                f"sil={self.similarity_silhouette_score:.2f})"
            ),
            "implication": str(scale_info["strategy"]),
        },
        {
            "dimension": "demand_regime",
            "signal": "dominant_regime · zero_fraction · ADI · CV² · cold_start",
            "measured_value": (
                f"regime='{self.dominant_regime}' | zeros={self.zero_fraction:.1%} | "
                f"ADI={self.median_adi:.2f} | CV²={self.median_cv2:.2f} | "
                f"cold_start={cold_share:.1%} | "
                f"donor_sim={self.cold_start_donor_similarity:.2f}"
            ),
            "implication": (
                "Intermittent/lumpy zeros trigger MASE scoring and Croston/TSB specialists "
                "with regime routing."
                if (
                    self.zero_fraction >= 0.25
                    or self.dominant_regime in ("intermittent", "lumpy")
                )
                else (
                    "Mixed mature and short cold-start series favor cross-series pooling and "
                    "SBC regime routing."
                    if cold_share > 0.05
                    else (
                        "Smooth/continuous series support WAPE scoring and standard "
                        "lag/seasonal models."
                    )
                )
            ),
        },
        {
            "dimension": "seasonality_and_scaling",
            "signal": "seasonal_acf · level_vol_corr · end_to_start_ratio",
            "measured_value": (
                f"acf_season={self.median_acf_season:.2f} | "
                f"level_vol_corr={self.level_vol_corr:.2f} | "
                f"growth_ratio={self.end_to_start_ratio:.2f}"
            ),
            "implication": (
                "Amplitude scales with level (multiplicative); log1p variance stabilization "
                "recommended."
                if (self.level_vol_corr >= 0.55 and self.end_to_start_ratio >= 1.35)
                else (
                    "Additive variance regime; standard linear target scaling is "
                    "well-conditioned."
                )
            ),
        },
        {
            "dimension": "breaks_and_outliers",
            "signal": "structural_break_share · outlier_spike_share",
            "measured_value": (
                f"breaks={self.structural_break_share:.1%} | "
                f"spikes={self.outlier_spike_share:.1%} | "
                f"ks_drift={self.residual_drift_ks_stat:.2f}"
            ),
            "implication": (
                "Elevated structural shifts or >6-sigma spikes trigger level_shift indicators "
                "and fold-safe stl_resid outlier scrubbing."
                if (self.structural_break_share >= 0.15 or self.outlier_spike_share >= 0.10)
                else (
                    "Clean historical trajectory; no aggressive outlier clipping required "
                    "in Pass 1."
                )
            ),
        },
        {
            "dimension": "hygiene_and_calendar",
            "signal": "leading_zeros · missing_gaps · censored_col",
            "measured_value": (
                f"leading_zeros={self.leading_zero_share:.1%} | "
                f"date_gaps={self.missing_date_gap_share:.1%} | "
                f"censored_col={self.censored_col or 'none'}"
            ),
            "implication": (
                "Pre-launch leading zeros, calendar gaps, or stockout censoring detected; "
                "enables automatic hygiene repair / latent demand reconstruction."
                if (
                    self.leading_zero_share >= 0.05
                    or self.missing_date_gap_share > 0.0
                    or self.censored_col
                )
                else "Contiguous date grid with no pre-launch zero padding or stockout flags."
            ),
        },
        {
            "dimension": "covariates",
            "signal": "future · past · static covariates",
            "measured_value": (
                f"{len(cov_list)} column(s): {', '.join(cov_list)}"
                if cov_list
                else "0 extra feature columns (pure univariate panel)"
            ),
            "implication": (
                "Benchmarks covariate models (@cov_all) against paired @univariate baselines "
                "and prunes low-attribution decoy columns in autofocus."
                if cov_list
                else "Univariate panel; prioritizes seasonal, state-space, lag-tree, and "
                "univariate foundation models."
            ),
        },
        {
            "dimension": "hierarchy_topology",
            "signal": "hierarchy_id_cols · node_count · non_negative · similarity_clusters",
            "measured_value": (
                f"cols={list(self.hierarchy_id_cols)} | "
                f"nodes={max(self.hierarchy_node_count, self.n_series)} | "
                f"non_negative={self.non_negative}"
                if self.hierarchy_id_cols
                else (
                    f"Flat panel (no hierarchy columns) | "
                    f"similarity_clusters={self.optimal_similarity_clusters} "
                    f"(sil={self.similarity_silhouette_score:.2f}) | "
                    f"non_negative={self.non_negative}"
                )
            ),
            "implication": (
                "Hierarchical tree detected; applies scale-aware coherent reconciliation "
                f"({', '.join(select_hierarchy_reconciliation_methods(self))}) with 0.0 "
                "aggregation residual."
                if self.hierarchy_id_cols
                else (
                    "Flat panel with distinct behavioral similarity clusters; supports "
                    "@similarity_global pooling and latent similarity_hierarchy reconciliation."
                    if self.has_similarity_clusters
                    else (
                        "Independent series; enforces output.floor=0.0 when history "
                        "is non-negative."
                    )
                )
            ),
        },
    ]
    if self.is_compositional_simplex:
        rows.append(
            {
                "dimension": "compositional_simplex",
                "signal": "compositional_simplex",
                "measured_value": (
                    f"simplex_total={self.simplex_total:.2f} | "
                    f"n_parts={self.n_series} | non_negative={self.non_negative}"
                ),
                "implication": (
                    "Constant-sum compositional simplex detected; routes Aitchison "
                    "log-ratio transforms (@transform_ilr / @transform_clr) with "
                    f"features.simplex_sum={self.simplex_total:.2f}."
                ),
            }
        )
    return pd.DataFrame(
        rows,
        columns=["dimension", "signal", "measured_value", "implication"],
    )

to_dict

to_dict()

Serialize profile to a plain JSON-compatible dictionary.

Source code in src/scale_forecasting/auto_policy.py
def to_dict(self) -> dict[str, Any]:
    """Serialize profile to a plain JSON-compatible dictionary."""
    raw = asdict(self)
    for k, v in list(raw.items()):
        if isinstance(v, tuple):
            raw[k] = list(v)
    raw["scale_regime"] = self.scale_regime
    return raw

classify_scale_regime

classify_scale_regime(n_series)

Classify panel series count n_series into one of the 5 canonical scale regimes.

Source code in src/scale_forecasting/auto_policy.py
def classify_scale_regime(n_series: int) -> str:
    """Classify panel series count `n_series` into one of the 5 canonical scale regimes."""
    if n_series < 15:
        return "micro"
    if n_series < 200:
        return "small"
    if n_series < 2500:
        return "medium"
    if n_series < 25000:
        return "large"
    return "hyperscale"

estimate_continue_confidence

estimate_continue_confidence(
    profile,
    pass_index,
    max_passes,
    diagnostics_summary,
    proposed_mutations,
    *,
    remaining_minutes=None,
    next_pass_p50_minutes=0.5,
    min_confidence=0.35,
)

Compute calibrated continuation confidence $C_{k+1} \in [0, 1]$ and expected FVA gain.

Combines five empirical diagnostic signals: 1. Number and specificity of actionable mutations proposed (proposed_mutations). 2. Residual autocorrelation ($|\rho_1|$) indicating uncaptured temporal structure. 3. Residual heteroskedasticity / multiplicative scaling signal. 4. Decoy covariate noise share that can be pruned. 5. Horizon decay crossover step $h^*$.

If residuals are already white noise (white_noise_residuals=True) and no structural mutation is warranted (as on dgp_12_already_optimal_white_noise), confidence drops below 0.20 and should_continue is False.

Source code in src/scale_forecasting/auto_policy.py
def estimate_continue_confidence(
    profile: PanelAutoProfile,
    pass_index: int,
    max_passes: int,
    diagnostics_summary: dict[str, Any],
    proposed_mutations: Sequence[dict[str, str]],
    *,
    remaining_minutes: float | None = None,
    next_pass_p50_minutes: float = 0.5,
    min_confidence: float = 0.35,
) -> dict[str, Any]:
    """Compute calibrated continuation confidence $C_{k+1} \\in [0, 1]$ and expected FVA gain.

    Combines five empirical diagnostic signals:
    1. Number and specificity of actionable mutations proposed (`proposed_mutations`).
    2. Residual autocorrelation ($|\\rho_1|$) indicating uncaptured temporal structure.
    3. Residual heteroskedasticity / multiplicative scaling signal.
    4. Decoy covariate noise share that can be pruned.
    5. Horizon decay crossover step $h^*$.

    If residuals are already white noise (`white_noise_residuals=True`) and no structural mutation
    is warranted (as on `dgp_12_already_optimal_white_noise`), confidence drops below `0.20` and
    `should_continue` is ``False``.
    """
    _ = (profile, diagnostics_summary)
    if pass_index >= max_passes:
        return {
            "confidence": 0.0,
            "expected_gain_pct": 0.0,
            "should_continue": False,
            "reason": f"Reached max_passes={max_passes} for the selected exposure tier.",
        }

    if remaining_minutes is not None and next_pass_p50_minutes > remaining_minutes:
        return {
            "confidence": 0.0,
            "expected_gain_pct": 0.0,
            "should_continue": False,
            "reason": (
                f"Pre-loop wall-clock gate: predicted Pass {pass_index + 1} duration "
                f"({next_pass_p50_minutes:.2f}m) exceeds remaining budget "
                f"({remaining_minutes:.2f}m)."
            ),
        }

    if not proposed_mutations:
        return {
            "confidence": 0.12,
            "expected_gain_pct": 0.2,
            "should_continue": False,
            "reason": (
                "Residuals are statistically clean (white-noise floor reached) with no "
                "high-confidence structural mutations remaining."
            ),
        }

    # Score the strength of the proposed interventions
    th = evolved_policy_thresholds()
    action_weights = dict(
        th.get(
            "action_weights",
            {
                "prune_decoy_covariates": (0.88, 7.2),
                "inject_transform_log1p": (0.86, 8.5),
                "inject_transform_simplex": (0.87, 8.0),
                "inject_direct_horizon_models": (0.82, 5.4),
                "enable_level_shift": (0.84, 7.0),
                "enable_stl_resid_outlier_scrubbing": (0.80, 5.0),
                "inject_intermittent_specialists": (0.85, 6.2),
                "enable_cold_start_pooling": (0.83, 6.0),
                "enable_cold_start_transfer": (0.85, 6.5),
                "enable_cold_start_donor_transfer": (0.85, 6.5),
                "enable_adaptive_conformal": (0.82, 5.2),
                "enable_aci_conformal_tracking": (0.82, 5.2),
                "refine_hierarchical_coherence": (0.82, 5.8),
                "enable_temporal_reconciliation": (0.78, 4.8),
                "refine_probabilistic_quantiles": (0.84, 6.4),
                "synthesize_winning_dag_branches": (0.80, 4.5),
                "escalate_model_diversity": (0.60, 2.6),
            },
        )
    )

    best_conf = 0.25
    total_expected_gain = 0.0
    for mut in proposed_mutations:
        act = mut.get("action", "")
        c_w, g_w = action_weights.get(act, (0.50, 2.0))
        best_conf = max(best_conf, float(c_w))
        total_expected_gain += float(g_w)

    # Discount confidence on later passes (diminishing returns)
    decay_base = float(th.get("pass_decay_factor", 0.78))
    decay = 1.0 if pass_index == 1 else (decay_base ** (pass_index - 1))
    confidence = float(min(0.96, max(0.05, best_conf * decay)))
    expected_gain_pct = float(round(min(25.0, total_expected_gain * decay), 2))

    should_continue = confidence >= min_confidence
    if should_continue:
        actions_str = ", ".join(m.get("action", "refine") for m in proposed_mutations)
        reason = (
            f"Pass {pass_index + 1} approved (confidence={confidence:.2f} >= {min_confidence:.2f}, "
            f"expected FVA gain ~+{expected_gain_pct:.1f}% via {actions_str})."
        )
    else:
        reason = (
            f"Stopping after Pass {pass_index}: continuation confidence {confidence:.2f} "
            f"is below threshold {min_confidence:.2f} (expected gain +{expected_gain_pct:.1f}%)."
        )

    return {
        "confidence": round(confidence, 3),
        "expected_gain_pct": expected_gain_pct,
        "should_continue": should_continue,
        "reason": reason,
    }

evolved_policy_thresholds

evolved_policy_thresholds()

Return calibrated decision thresholds and action weights for auto_policy.

Evolved via Mode A AlphaEvolve (gemini-3.8-flash + gemini-4-argon) across the 20 canonical synthetic DGP benchmarks and multi-scale empirical cell bank.

Source code in src/scale_forecasting/auto_policy.py
def evolved_policy_thresholds() -> dict[str, Any]:
    """Return calibrated decision thresholds and action weights for `auto_policy`.

    Evolved via Mode A AlphaEvolve (`gemini-3.8-flash` + `gemini-4-argon`) across the
    20 canonical synthetic DGP benchmarks and multi-scale empirical cell bank.
    """
    return {
        "intermittent_share_min": 0.165,
        "log1p_level_vol_corr_min": 0.635,
        "log1p_growth_ratio_min": 1.336,
        "resid_hetero_min": 0.30,
        "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.70,
        "first_light_include_regression_lags": True,
        "first_light_selection_rule": "best_single",
        "first_light_ensemble_strategies": ["inverse_error", "mean"],
        "tree_n_estimators_fast": 60,
        "enable_similarity_global": True,
        "similarity_silhouette_threshold": 0.30,
        "action_weights": {
            "prune_decoy_covariates": (0.86, 6.6),
            "fallback_to_plain_univariate": (0.65, 7.4),
            "synthesize_exog_lags": (0.92, 5.0),
            "inject_monotone_guardrails": (0.88, 4.2),
            "inject_transform_log1p": (0.92, 10.4),
            "inject_transform_simplex": (0.87, 8.0),
            "inject_direct_horizon_models": (0.84, 5.7),
            "inject_similarity_global": (0.86, 6.4),
            "inject_similarity_cold_start": (0.85, 5.2),
            "enable_level_shift": (0.92, 11.5),
            "enable_sliding_window_backtest": (0.67, 4.3),
            "enable_stl_resid_outlier_scrubbing": (0.96, 5.9),
            "inject_intermittent_specialists": (0.68, 5.3),
            "enable_cold_start_pooling": (0.94, 3.4),
            "enable_cold_start_transfer": (0.85, 5.2),
            "enable_cold_start_donor_transfer": (0.85, 5.2),
            "enable_similarity_hierarchy": (0.83, 5.5),
            "enable_adaptive_conformal": (0.82, 4.1),
            "enable_aci_conformal_tracking": (0.82, 4.1),
            "refine_hierarchical_coherence": (0.86, 10.5),
            "enable_temporal_reconciliation": (0.78, 4.8),
            "refine_probabilistic_quantiles": (0.66, 2.9),
            "refine_censored_demand_models": (0.96, 7.2),
            "escalate_bigquery_foundation": (0.66, 2.0),
            "synthesize_winning_dag_branches": (0.65, 3.7),
            "escalate_model_diversity": (0.63, 2.7),
        },
    }

propose_autofocus_dag_branches

propose_autofocus_dag_branches(
    profile,
    prior_config_dict,
    pass_index=2,
    diagnostics_summary=None,
    *,
    tier="wide_field",
    where="auto",
    goal="accuracy",
    available_models=None,
)

Decompose Level-2 autofocus mutations into parallel Tournament DAG branches (2A..2C).

When only one hypothesis domain triggers (e.g., pure covariate pruning on dgp_04 or pure @transform_log1p on dgp_02), returns a single branch (pass_id="2"). When two or three orthogonal hypothesis domains trigger simultaneously (transform_and_hygiene, covariates_and_horizon, regime_and_specialists), returns independent branch specifications (pass_id="2A", "2B", "2C") that each branch off Pass 1 (parent_pass_ids=("1",)), enabling isolated attribution of every mutation before Level-3 synthesis.

Source code in src/scale_forecasting/auto_policy.py
def propose_autofocus_dag_branches(
    profile: PanelAutoProfile | dict[str, Any],
    prior_config_dict: dict[str, Any] | PanelAutoProfile,
    pass_index: int | dict[str, Any] = 2,
    diagnostics_summary: dict[str, Any] | None = None,
    *,
    tier: str = "wide_field",
    where: str = "auto",
    goal: str = "accuracy",
    available_models: Sequence[str] | None = None,
) -> list[dict[str, Any]]:
    """Decompose Level-2 `autofocus` mutations into parallel Tournament DAG branches (`2A`..`2C`).

    When only one hypothesis domain triggers (e.g., pure covariate pruning on `dgp_04` or pure
    `@transform_log1p` on `dgp_02`), returns a single branch (`pass_id="2"`). When two or three
    orthogonal hypothesis domains trigger simultaneously (`transform_and_hygiene`,
    `covariates_and_horizon`, `regime_and_specialists`), returns independent branch specifications
    (`pass_id="2A"`, `"2B"`, `"2C"`) that each branch off Pass 1 (`parent_pass_ids=("1",)`),
    enabling isolated attribution of every mutation before Level-3 synthesis.
    """
    if (
        isinstance(profile, dict)
        and isinstance(prior_config_dict, PanelAutoProfile)
        and isinstance(pass_index, dict)
        and diagnostics_summary is None
    ):
        diagnostics_summary = pass_index
        pass_index = 2
        profile, prior_config_dict = prior_config_dict, profile
    assert isinstance(profile, PanelAutoProfile)
    assert isinstance(prior_config_dict, dict)
    if diagnostics_summary is None:
        diagnostics_summary = {}
    pass_idx_int = int(pass_index) if isinstance(pass_index, int) else 2

    full_proposal = propose_autofocus_pass(
        profile,
        prior_config_dict,
        pass_idx_int,
        diagnostics_summary,
        tier=tier,
        where=where,
        goal=goal,
        available_models=available_models,
    )
    all_mutations: list[dict[str, str]] = list(full_proposal.get("mutations", []))
    if not all_mutations:
        return []

    domain_order = (
        ("transform_and_hygiene", "Target Transform & Structural Hygiene"),
        ("covariates_and_horizon", "Covariate Pruning & Direct Horizon Specialists"),
        ("regime_and_specialists", "Regime Routing & Domain Model Specialists"),
    )
    domain_canonical_suffix = {
        "transform_and_hygiene": "A",
        "covariates_and_horizon": "B",
        "regime_and_specialists": "C",
    }
    muts_by_domain: dict[str, list[dict[str, str]]] = {
        dom: [m for m in all_mutations if m.get("domain", "regime_and_specialists") == dom]
        for dom, _ in domain_order
    }
    active_domains = [(dom, title) for dom, title in domain_order if muts_by_domain[dom]]

    if len(active_domains) <= 1:
        single_dom = active_domains[0][0] if active_domains else "regime_and_specialists"
        single_title = active_domains[0][1] if active_domains else "Targeted Refinement"
        canon_branch_id = f"{pass_idx_int}{domain_canonical_suffix.get(single_dom, 'C')}"
        return [
            {
                **full_proposal,
                "pass_id": str(pass_idx_int),
                "branch_id": canon_branch_id,
                "domain": single_dom,
                "parent_pass_ids": (str(pass_idx_int - 1),),
                "branch_hypothesis": single_title,
            }
        ]

    # Build one isolated branch per active hypothesis domain starting from prior_config_dict
    base_models = list(prior_config_dict.get("models", []))
    base_features = dict(prior_config_dict.get("features", {}))
    base_output = dict(prior_config_dict.get("output", {}))
    base_ensemble = dict(prior_config_dict.get("ensemble", {}))
    base_backtest = dict(prior_config_dict.get("backtest", {}))
    base_hierarchy = dict(prior_config_dict.get("hierarchy") or {})
    base_params = {k: dict(v) for k, v in dict(prior_config_dict.get("model_params", {})).items()}

    full_features = dict(full_proposal.get("features", base_features))
    full_output = dict(full_proposal.get("output", base_output))
    full_backtest = dict(full_proposal.get("backtest", base_backtest))
    full_hierarchy = dict(full_proposal.get("hierarchy") or base_hierarchy)
    full_params = dict(full_proposal.get("model_params", base_params))

    branches: list[dict[str, Any]] = []
    suffixes = ("A", "B", "C")
    for idx, (dom, title) in enumerate(active_domains):
        branch_id = f"{pass_idx_int}{suffixes[idx]}"
        canon_branch_id = f"{pass_idx_int}{domain_canonical_suffix.get(dom, suffixes[idx])}"
        dom_muts = muts_by_domain[dom]
        b_models = list(base_models)
        b_added: list[str] = []
        b_features = dict(base_features)
        b_output = dict(base_output)
        b_ensemble = dict(base_ensemble)
        b_backtest = dict(base_backtest)
        b_hierarchy = dict(base_hierarchy)
        b_params = {k: dict(v) for k, v in base_params.items()}
        b_strats = list(b_ensemble.get("strategies", ["inverse_error"]))

        if dom == "transform_and_hygiene":
            for m in full_proposal["models"]:
                if ("@transform_" in m) and m not in b_models:
                    b_models.append(m)
                    b_added.append(m)
                    if m in full_params:
                        b_params[m] = dict(full_params[m])
            for fkey in ("transform", "level_shift", "outlier_policy", "simplex_sum"):
                if fkey in full_features:
                    b_features[fkey] = full_features[fkey]
            if "scheme" in full_backtest:
                b_backtest["scheme"] = full_backtest["scheme"]
            if "champion" not in b_strats:
                b_strats.append("champion")
        elif dom == "covariates_and_horizon":
            for m in full_proposal["models"]:
                if (
                    "@direct" in m or "@monotone" in m or "@similarity_global" in m
                ) and m not in b_models:
                    b_models.append(m)
                    b_added.append(m)
                    if m in full_params:
                        b_params[m] = dict(full_params[m])
            if "future_covariates" in full_features:
                b_features["future_covariates"] = list(full_features["future_covariates"])
            if "exog_lags" in full_features and isinstance(full_features["exog_lags"], dict):
                b_features["exog_lags"] = dict(full_features["exog_lags"])
            if "monotonic_constraints" in full_features and isinstance(
                full_features["monotonic_constraints"], dict
            ):
                b_features["monotonic_constraints"] = dict(full_features["monotonic_constraints"])
            for sf_key in ("similarity_cluster_feature", "similarity_n_clusters"):
                if sf_key in full_features:
                    b_features[sf_key] = full_features[sf_key]
            for s_tag in ("horizon_specialist", "champion"):
                if s_tag not in b_strats:
                    b_strats.append(s_tag)
        else:
            for m in full_proposal["models"]:
                if (
                    m not in b_models
                    and "@transform_" not in m
                    and "@direct" not in m
                    and "@monotone" not in m
                    and "@similarity_global" not in m
                ):
                    b_models.append(m)
                    b_added.append(m)
                    if m in full_params:
                        b_params[m] = dict(full_params[m])
            for rf_key in (
                "regime_routing",
                "cold_start_transfer",
                "cold_start_matching",
                "similarity_cluster_feature",
                "similarity_n_clusters",
            ):
                if rf_key in full_features:
                    b_features[rf_key] = full_features[rf_key]
            if full_hierarchy:
                if "reconciliation_methods" in full_hierarchy:
                    b_hierarchy["reconciliation_methods"] = list(
                        full_hierarchy["reconciliation_methods"]
                    )
                for hkey in (
                    "reconcile_temporal",
                    "temporal_aggregations",
                    "cross_temporal",
                    "spatial_temporal_weight",
                    "similarity_hierarchy",
                    "similarity_n_clusters",
                ):
                    if hkey in full_hierarchy:
                        b_hierarchy[hkey] = full_hierarchy[hkey]
            for ok in ("point_forecast", "target_quantile", "calibration_method", "aci_gamma"):
                if ok in full_output:
                    b_output[ok] = full_output[ok]
            for s_tag in full_proposal.get("ensemble", {}).get("strategies", []):
                if s_tag not in b_strats:
                    b_strats.append(s_tag)

        b_ensemble["strategies"] = b_strats
        branches.append(
            {
                "pass_id": branch_id,
                "branch_id": canon_branch_id,
                "domain": dom,
                "parent_pass_ids": ("1",),
                "branch_hypothesis": title,
                "models": b_models,
                "added_models": b_added,
                "model_params": b_params,
                "features": b_features,
                "output": b_output,
                "ensemble": b_ensemble,
                "backtest": b_backtest,
                "hierarchy": b_hierarchy or None,
                "mutations": dom_muts,
            }
        )

    return branches

propose_autofocus_pass

propose_autofocus_pass(
    profile,
    prior_config_dict,
    pass_index=2,
    diagnostics_summary=None,
    *,
    tier="wide_field",
    where="auto",
    goal="accuracy",
    available_models=None,
)

Closed-Loop Observe -> Review -> Re-Plan: propose surgical mutations for Pass pass_index.

Inspects out-of-fold econometric diagnostics from Pass pass_index - 1 (FVA waterfall, feature attributions, horizon decay crossover $h^*$, directional bias, SBC demand regime sparsity/cold-start share, hierarchy structure, and residual heteroskedasticity/autocorrelation) and returns a dictionary of targeted config updates plus structured evidence rationales.

Source code in src/scale_forecasting/auto_policy.py
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
def propose_autofocus_pass(
    profile: PanelAutoProfile | dict[str, Any],
    prior_config_dict: dict[str, Any] | PanelAutoProfile,
    pass_index: int | dict[str, Any] = 2,
    diagnostics_summary: dict[str, Any] | None = None,
    *,
    tier: str = "wide_field",
    where: str = "auto",
    goal: str = "accuracy",
    available_models: Sequence[str] | None = None,
) -> Any:
    """Closed-Loop `Observe -> Review -> Re-Plan`: propose surgical mutations for Pass `pass_index`.

    Inspects out-of-fold econometric diagnostics from Pass `pass_index - 1` (FVA waterfall,
    feature attributions, horizon decay crossover $h^*$, directional bias, SBC demand regime
    sparsity/cold-start share, hierarchy structure, and residual heteroskedasticity/autocorrelation)
    and returns a dictionary of targeted config updates plus structured evidence rationales.
    """
    _return_mutations_only = False
    if isinstance(profile, dict) and isinstance(prior_config_dict, PanelAutoProfile):
        _return_mutations_only = True
        _real_prior = dict(profile)
        _real_profile = prior_config_dict
        if isinstance(pass_index, dict):
            _real_diag = dict(pass_index)
            _real_pass_idx = int(diagnostics_summary) if isinstance(diagnostics_summary, int) else 2
        else:
            _real_pass_idx = int(pass_index)
            _real_diag = dict(diagnostics_summary or {})
        profile = _real_profile
        prior_config_dict = _real_prior
        pass_index = _real_pass_idx
        diagnostics_summary = _real_diag
    else:
        assert isinstance(profile, PanelAutoProfile)
        assert isinstance(prior_config_dict, dict)
        pass_index = int(pass_index) if isinstance(pass_index, int) else 2
        diagnostics_summary = dict(diagnostics_summary or {})

    avail = set(
        available_models
        if available_models is not None
        else (
            "naive_seasonal",
            "naive_mean",
            "naive_moving_average",
            "theta",
            "holtwinters",
            "stl_bagging",
            "croston",
            "fft",
            "autoets",
            "regression_lags",
            "lightgbm",
            "xgboost",
            "catboost",
            "random_forest",
            "tide",
            "tsmixer",
            "chronos_bolt",
            "chronos2",
            "timesfm_torch",
        )
    )
    current_models: list[str] = list(prior_config_dict.get("models", []))
    features_cfg: dict[str, Any] = dict(prior_config_dict.get("features", {}))
    backtest_cfg: dict[str, Any] = dict(prior_config_dict.get("backtest", {}))
    hierarchy_cfg: dict[str, Any] = dict(prior_config_dict.get("hierarchy", {}))
    output_cfg: dict[str, Any] = dict(prior_config_dict.get("output", {}))
    ensemble_cfg: dict[str, Any] = dict(prior_config_dict.get("ensemble", {}))
    model_params: dict[str, dict[str, Any]] = {
        k: dict(v) for k, v in dict(prior_config_dict.get("model_params", {})).items()
    }

    mutations: list[dict[str, str]] = []
    added_models: list[str] = []
    th = evolved_policy_thresholds()
    n_folds = int(prior_config_dict.get("backtest", {}).get("n_folds", 1))
    decision_metric = str(
        prior_config_dict.get("backtest", {}).get(
            "decision_metric", diagnostics_summary.get("decision_metric", "wape")
        )
    )

    is_intermittent_heavy = (
        profile.dominant_regime in ("intermittent", "lumpy")
        or profile.zero_fraction >= 0.20
        or profile.median_adi >= 1.32
        or (
            profile.regime_shares.get("intermittent", 0.0) + profile.regime_shares.get("lumpy", 0.0)
        )
        >= float(th.get("intermittent_share_min", 0.25))
    )
    has_cold_start = (
        profile.dominant_regime == "cold_start"
        or profile.regime_shares.get("cold_start", 0.0) > 0.0
        or profile.min_n_obs < max(28, 2 * profile.horizon)
    )
    has_hierarchy = bool(profile.hierarchy_id_cols) or bool(
        prior_config_dict.get("hierarchy", {}).get("enabled", False)
    )
    is_probabilistic_goal = goal in ("service_level", "probabilistic") or decision_metric in (
        "pinball",
        "pinball_loss",
        "interval_score",
        "wis",
    )

    # 0. Stationary White-Noise Early Exit: only when the panel is genuinely smooth stationary
    # white noise (not intermittent, not cold-start, not hierarchical, not service-level quantile).
    wn_stop = bool(th.get("require_white_noise_stop", True))
    if (
        wn_stop
        and where != "bigquery"
        and not is_intermittent_heavy
        and not has_cold_start
        and not has_hierarchy
        and not is_probabilistic_goal
        and not profile.is_compositional_simplex
        and not bool(diagnostics_summary.get("coverage_drift_detected", False))
        and not bool(diagnostics_summary.get("cold_start_donor_transfer_recommended", False))
        and abs(profile.end_to_start_ratio - 1.0) < float(th.get("white_noise_growth_tol", 0.15))
        and profile.median_acf_season < float(th.get("white_noise_acf_season_max", 0.18))
        and not profile.future_covariates
        and profile.structural_break_share < 0.10
        and profile.outlier_spike_share < 0.10
        and diagnostics_summary.get("white_noise_residuals", False)
    ):
        if _return_mutations_only:
            return mutations
        return {
            "models": current_models,
            "added_models": added_models,
            "model_params": model_params,
            "features": features_cfg,
            "output": output_cfg,
            "ensemble": ensemble_cfg,
            "backtest": backtest_cfg,
            "hierarchy": hierarchy_cfg,
            "mutations": mutations,
        }

    # 1. Covariate Pruning, Plain Univariate Fallback & Exogenous Lag Synthesis
    noisy_covs: list[str] = list(diagnostics_summary.get("zero_or_negative_covariates", []))
    positive_covs: list[str] = list(diagnostics_summary.get("positive_covariates", []))
    curr_fut = list(features_cfg.get("future_covariates", []))
    cov_fva_pct = float(diagnostics_summary.get("covariate_fva_pct", 0.0))
    if noisy_covs and positive_covs and len(curr_fut) > len(positive_covs):
        pruned_fut = [c for c in curr_fut if c in positive_covs]
        if pruned_fut and pruned_fut != curr_fut:
            features_cfg["future_covariates"] = pruned_fut
            mutations.append(
                {
                    "action": "prune_decoy_covariates",
                    "domain": "covariates_and_horizon",
                    "parameter": "features.future_covariates",
                    "old_value": str(curr_fut),
                    "new_value": str(pruned_fut),
                    "evidence": f"noisy_covariates={noisy_covs}, positive_drivers={positive_covs}",
                    "rationale": (
                        f"Pruned {len(curr_fut) - len(pruned_fut)} zero/negative-value decoy "
                        f"covariate(s) ({', '.join(noisy_covs)}) identified by feature attribution "
                        "and covariate FVA audit."
                    ),
                }
            )
    elif curr_fut and not positive_covs and len(noisy_covs) >= len(curr_fut) and cov_fva_pct <= 0.0:
        features_cfg["future_covariates"] = []
        for uni_cand in ("theta", "holtwinters"):
            if uni_cand in avail and uni_cand not in current_models:
                current_models.append(uni_cand)
                added_models.append(uni_cand)
        mutations.append(
            {
                "action": "fallback_to_plain_univariate",
                "domain": "covariates_and_horizon",
                "parameter": "features.future_covariates",
                "old_value": str(curr_fut),
                "new_value": "[] (plain univariate)",
                "evidence": (
                    f"all_covariates_noisy={noisy_covs}, covariate_fva_pct={cov_fva_pct:+.2f}%"
                ),
                "rationale": (
                    "All candidate future covariates degraded or failed to improve validation "
                    "accuracy against plain univariate anchors; dropping all decoy covariates "
                    "and reverting to plain univariate forecasting."
                ),
            }
        )

    if (
        bool(diagnostics_summary.get("exog_lag_signal", False))
        and features_cfg.get("future_covariates")
        and not features_cfg.get("exog_lags")
    ):
        exog_lag_steps = [1, 2, 4] if str(profile.freq).upper().startswith("W") else [1, 2, 7]
        fut_for_lags = [str(c) for c in features_cfg.get("future_covariates", [])]
        exog_lags_dict = {c: list(exog_lag_steps) for c in fut_for_lags}
        features_cfg["exog_lags"] = exog_lags_dict
        mutations.append(
            {
                "action": "synthesize_exog_lags",
                "domain": "covariates_and_horizon",
                "parameter": "features.exog_lags",
                "old_value": "{}",
                "new_value": str(exog_lags_dict),
                "evidence": "exog_lag_signal=True (post-promo pull-forward / lagged response)",
                "rationale": (
                    "Residuals exhibit lagged correlation with exogenous drivers; synthesizing "
                    f"lagged covariate features ({exog_lag_steps}) to capture post-promo dips "
                    "and delayed price/promotion effects."
                ),
            }
        )

    # 1.5. Monotonic Price / Promo Elasticity Guardrail Injection
    eff_fut_covs = [str(c) for c in features_cfg.get("future_covariates", [])]
    eff_past_covs = [str(c) for c in features_cfg.get("past_covariates", [])]
    active_cov_set = set(eff_fut_covs) | set(eff_past_covs)
    raw_mono = dict(profile.monotonic_constraints) or infer_monotonic_constraints(
        [*eff_fut_covs, *eff_past_covs]
    )
    active_mono = {k: int(v) for k, v in raw_mono.items() if k in active_cov_set and int(v) != 0}
    has_monotone_variant = any("@monotone" in m for m in current_models)
    if active_mono and not has_monotone_variant:
        mono_candidates = (
            ("lightgbm", "regression_lags")
            if tier in ("first_light", "wide_field")
            else ("lightgbm", "xgboost", "regression_lags")
        )
        mono_added: list[str] = []
        for mc in mono_candidates:
            if mc in avail:
                spec_m = f"{mc}@monotone"
                if spec_m not in current_models:
                    current_models.append(spec_m)
                    added_models.append(spec_m)
                    mono_added.append(spec_m)
                if mc in ("lightgbm", "xgboost") and tier in ("first_light", "wide_field"):
                    model_params.setdefault(
                        spec_m, {"n_estimators": int(th.get("tree_n_estimators_fast", 55))}
                    )
        old_mono = dict(prior_config_dict.get("features", {}).get("monotonic_constraints", {}))
        features_cfg["monotonic_constraints"] = active_mono
        if mono_added:
            strats_m = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "champion" not in strats_m:
                strats_m.append("champion")
            ensemble_cfg["strategies"] = strats_m
            mutations.append(
                {
                    "action": "inject_monotone_guardrails",
                    "domain": "covariates_and_horizon",
                    "parameter": "models + features.monotonic_constraints",
                    "old_value": str(old_mono or "unconstrained"),
                    "new_value": f"{', '.join(mono_added)} ({active_mono})",
                    "evidence": f"structural_drivers={list(active_mono.keys())}",
                    "rationale": (
                        "Injecting sign-constrained @monotone learners and monotonic_constraints "
                        "to prevent wrong-signed price/promotion elasticity under collinearity."
                    ),
                }
            )

    # 2. Multiplicative Variance / Log1p Transform Exploration
    resid_hetero = float(diagnostics_summary.get("residual_heteroskedasticity", 0.0))
    has_log_variant = features_cfg.get("transform") in ("log1p", "boxcox") or any(
        "@transform_log1p" in m or "@transform_boxcox" in m for m in current_models
    )
    if (
        not profile.is_compositional_simplex
        and profile.non_negative
        and not profile.integer_valued
        and not has_log_variant
        and (
            resid_hetero >= float(th.get("resid_hetero_min", 0.42))
            or (
                profile.level_vol_corr >= float(th.get("log1p_level_vol_corr_min", 0.65))
                and profile.end_to_start_ratio >= float(th.get("log1p_growth_ratio_min", 1.45))
            )
        )
    ):
        log_added: list[str] = []
        log_candidates = (
            ("lightgbm", "regression_lags", "theta")
            if tier in ("first_light", "wide_field")
            else ("lightgbm", "xgboost", "regression_lags", "theta")
        )
        for cand in log_candidates:
            if cand in avail:
                spec = f"{cand}@transform_log1p"
                if spec not in current_models:
                    current_models.append(spec)
                    added_models.append(spec)
                    log_added.append(spec)
                if cand in ("lightgbm", "xgboost") and tier in ("first_light", "wide_field"):
                    model_params.setdefault(
                        spec, {"n_estimators": int(th.get("tree_n_estimators_fast", 55))}
                    )
        if log_added:
            strats = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "champion" not in strats:
                strats.append("champion")
            ensemble_cfg["strategies"] = strats
            mutations.append(
                {
                    "action": "inject_transform_log1p",
                    "domain": "transform_and_hygiene",
                    "parameter": "models",
                    "old_value": "linear_scale_only",
                    "new_value": ", ".join(log_added),
                    "evidence": (
                        f"residual_heteroskedasticity={resid_hetero:.2f}, "
                        f"level_vol_corr={profile.level_vol_corr:.2f}"
                    ),
                    "rationale": (
                        "Residuals exhibit level-dependent variance; injecting @transform_log1p "
                        "variants while reusing Pass 1 linear models via cell borrowing."
                    ),
                }
            )

    # 2.5. Compositional Simplex Log-Ratio Exploration (@transform_ilr / @transform_clr)
    if profile.is_compositional_simplex and where != "bigquery":
        simplex_added: list[str] = []
        simplex_total_val = round(float(profile.simplex_total or 1.0), 4)
        for cand, tag in (
            ("lightgbm", "transform_ilr"),
            ("regression_lags", "transform_ilr"),
            ("theta", "transform_clr"),
            ("lightgbm", "transform_clr"),
        ):
            if cand in avail:
                spec_s = f"{cand}@{tag}"
                if spec_s not in current_models:
                    current_models.append(spec_s)
                    added_models.append(spec_s)
                    simplex_added.append(spec_s)
                if cand == "lightgbm" and tier in ("first_light", "wide_field"):
                    model_params.setdefault(
                        spec_s, {"n_estimators": int(th.get("tree_n_estimators_fast", 55))}
                    )
        features_cfg["simplex_sum"] = simplex_total_val
        if simplex_added:
            strats_s = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "champion" not in strats_s:
                strats_s.append("champion")
            ensemble_cfg["strategies"] = strats_s
            mutations.append(
                {
                    "action": "inject_transform_simplex",
                    "domain": "transform_and_hygiene",
                    "parameter": "models + features.simplex_sum",
                    "old_value": str(prior_config_dict.get("features", {}).get("simplex_sum")),
                    "new_value": f"{', '.join(simplex_added)} (simplex_sum={simplex_total_val})",
                    "evidence": (
                        f"is_compositional_simplex=True, simplex_total={simplex_total_val}"
                    ),
                    "rationale": (
                        "Panel series form a constant-sum compositional simplex; injecting "
                        "Aitchison @transform_ilr and @transform_clr variants with exact "
                        "post-forecast simplex closure."
                    ),
                }
            )

    # 3. Lead-Time Horizon Crossover -> Direct Multi-Horizon Variants + Horizon Specialist
    crossover_step = diagnostics_summary.get("horizon_crossover_step")
    late_decay_ratio = float(diagnostics_summary.get("late_horizon_degradation_ratio", 1.0))
    has_direct = any("@direct" in m for m in current_models)
    has_specialist_regime = (
        is_intermittent_heavy or has_hierarchy or is_probabilistic_goal or has_cold_start
    )
    if not has_direct and (
        (isinstance(crossover_step, int) and 2 <= crossover_step < profile.horizon)
        or (
            not has_specialist_regime
            and late_decay_ratio >= float(th.get("direct_horizon_decay_ratio_min", 1.38))
        )
    ):
        direct_added: list[str] = []
        direct_candidates = (
            ("regression_lags", "lightgbm")
            if tier in ("first_light", "wide_field")
            else ("regression_lags", "lightgbm", "xgboost")
        )
        for ml_cand in direct_candidates:
            if ml_cand in avail:
                spec = f"{ml_cand}@direct"
                if spec not in current_models:
                    current_models.append(spec)
                    added_models.append(spec)
                    direct_added.append(spec)
                if ml_cand in ("lightgbm", "xgboost") and tier in ("first_light", "wide_field"):
                    model_params.setdefault(spec, {"n_estimators": 45})
        if direct_added:
            strats_hd = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "horizon_specialist" not in strats_hd:
                strats_hd.append("horizon_specialist")
            ensemble_cfg["strategies"] = strats_hd
            mutations.append(
                {
                    "action": "inject_direct_horizon_models",
                    "domain": "covariates_and_horizon",
                    "parameter": "models + ensemble.strategies",
                    "old_value": str(prior_config_dict.get("ensemble", {}).get("strategies")),
                    "new_value": f"{', '.join(direct_added)} + horizon_specialist",
                    "evidence": (
                        f"horizon_crossover_step={crossover_step}, "
                        f"late_horizon_degradation_ratio={late_decay_ratio:.2f}"
                    ),
                    "rationale": (
                        "Recursive lag rollouts degrade beyond short lead times; adding @direct "
                        "horizon models and enabling 'horizon_specialist' ensembling."
                    ),
                }
            )

    # 4. Structural Breaks & Outlier Spikes Discovered in Post-Run Residual Audit
    cp_share = float(diagnostics_summary.get("change_point_share", profile.structural_break_share))
    anom_share = float(diagnostics_summary.get("anomaly_share", profile.outlier_spike_share))
    if cp_share >= float(th.get("structural_break_share_min", 0.15)) and not features_cfg.get(
        "level_shift", False
    ):
        features_cfg["level_shift"] = True
        mutations.append(
            {
                "action": "enable_level_shift",
                "domain": "transform_and_hygiene",
                "parameter": "features.level_shift",
                "old_value": "False",
                "new_value": "True",
                "evidence": f"change_point_share={cp_share:.1%}",
                "rationale": (
                    "Post-fit change-point audit flagged structural level shifts; enabling "
                    "binary-segmentation step indicators."
                ),
            }
        )
    if (
        anom_share >= float(th.get("outlier_spike_share_min", 0.10))
        and features_cfg.get("outlier_policy", "none") == "none"
    ):
        features_cfg["outlier_policy"] = "stl_resid"
        mutations.append(
            {
                "action": "enable_stl_resid_outlier_scrubbing",
                "domain": "transform_and_hygiene",
                "parameter": "features.outlier_policy",
                "old_value": "none",
                "new_value": "stl_resid",
                "evidence": f"anomaly_share={anom_share:.1%}",
                "rationale": (
                    "Residual anomaly audit flagged extreme historical spikes; enabling "
                    "fold-safe STL residual outlier scrubbing."
                ),
            }
        )
    if (
        bool(diagnostics_summary.get("sliding_window_recommended", False))
        and backtest_cfg.get("scheme", "expanding") == "expanding"
        and profile.median_n_obs >= max(180, 4 * profile.horizon)
    ):
        backtest_cfg["scheme"] = "sliding"
        mutations.append(
            {
                "action": "enable_sliding_window_backtest",
                "domain": "transform_and_hygiene",
                "parameter": "backtest.scheme",
                "old_value": "expanding",
                "new_value": "sliding",
                "evidence": (
                    f"change_point_share={cp_share:.1%}, median_n_obs={profile.median_n_obs}"
                ),
                "rationale": (
                    "Persistent structural breaks with deep history bias expanding-window folds "
                    "toward pre-shift regimes; switching to sliding-window cross-validation."
                ),
            }
        )

    # 5. Intermittent / Lumpy Demand Specialist Escalation (dgp_03)
    if is_intermittent_heavy:
        inter_added: list[str] = []
        for inter_spec in ("naive_mean", "croston@classic", "croston@sba", "croston@tsb"):
            base_i = inter_spec.split("@", 1)[0]
            if base_i in avail and inter_spec not in current_models:
                current_models.append(inter_spec)
                added_models.append(inter_spec)
                inter_added.append(inter_spec)
        if inter_added:
            features_cfg["regime_routing"] = True
            strats_i = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            for s_i in ("champion", "median"):
                if s_i not in strats_i:
                    strats_i.append(s_i)
            ensemble_cfg["strategies"] = strats_i
            mutations.append(
                {
                    "action": "inject_intermittent_specialists",
                    "domain": "regime_and_specialists",
                    "parameter": "models + features.regime_routing",
                    "old_value": (
                        f"regime_routing="
                        f"{prior_config_dict.get('features', {}).get('regime_routing')}"
                    ),
                    "new_value": f"+{', '.join(inter_added)}, regime_routing=True",
                    "evidence": (
                        f"zero_fraction={profile.zero_fraction:.1%}, "
                        f"median_adi={profile.median_adi:.2f}, regime={profile.dominant_regime}"
                    ),
                    "rationale": (
                        "High zero-inflation and inter-demand intervals require dedicated "
                        "Syntetos-Boylan (SBA), Classic Croston, and unbiased level anchors "
                        "under SBC demand regime routing."
                    ),
                }
            )

    # 6. Cold-Start & Mixed-History Cross-Series Pooling / Donor Transfer Escalation (dgp_11)
    cold_start_donor_sim = max(
        float(getattr(profile, "cold_start_donor_similarity", 0.0)),
        float(diagnostics_summary.get("cold_start_donor_similarity", 0.0)),
    )
    cold_start_rec = bool(diagnostics_summary.get("cold_start_donor_transfer_recommended", False))
    if (
        has_cold_start or cold_start_donor_sim > 0.0 or cold_start_rec
    ) and not is_intermittent_heavy:
        cs_added: list[str] = []
        for cs_cand in ("holtwinters", "regression_lags", "xgboost"):
            if cs_cand in avail and cs_cand not in current_models:
                current_models.append(cs_cand)
                added_models.append(cs_cand)
                cs_added.append(cs_cand)
                if cs_cand == "xgboost" and tier in ("first_light", "wide_field"):
                    model_params.setdefault(
                        cs_cand, {"n_estimators": int(th.get("tree_n_estimators_fast", 55))}
                    )
        donor_transfer_active = (
            cold_start_rec
            or cold_start_donor_sim >= 0.65
            or (has_cold_start and profile.n_series >= 2 and profile.min_n_obs < 14)
        )
        if cs_added or donor_transfer_active:
            features_cfg["regime_routing"] = True
            if donor_transfer_active:
                features_cfg["cold_start_transfer"] = True
                if profile.has_similarity_clusters or profile.optimal_similarity_clusters >= 2:
                    features_cfg["cold_start_matching"] = "hybrid"
            strats_cs = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "champion" not in strats_cs:
                strats_cs.append("champion")
            if n_folds >= 2 and "nnls" not in strats_cs:
                strats_cs.append("nnls")
            ensemble_cfg["strategies"] = strats_cs
            mutations.append(
                {
                    "action": (
                        "enable_cold_start_transfer"
                        if donor_transfer_active
                        else "enable_cold_start_pooling"
                    ),
                    "domain": "regime_and_specialists",
                    "parameter": "models + features.regime_routing + features.cold_start_transfer",
                    "old_value": f"{len(current_models) - len(cs_added)} models",
                    "new_value": (
                        f"+{', '.join(cs_added) or 'existing'}, regime_routing=True, "
                        f"cold_start_transfer={donor_transfer_active}"
                    ),
                    "evidence": (
                        f"cold_start_share={profile.regime_shares.get('cold_start', 0.0):.1%}, "
                        f"min_n_obs={profile.min_n_obs}, "
                        f"cold_start_donor_similarity={cold_start_donor_sim:.2f}"
                    ),
                    "rationale": (
                        "Panel mixes mature donor series and short-history cold-start series; "
                        "enabling k-NN analog donor shrinkage transfer and SBC regime routing."
                    ),
                }
            )

    # 6b. Trajectory Similarity Clustering & Cross-Series Peer Context Escalation (Track P)
    sim_sil_min = float(th.get("similarity_silhouette_threshold", 0.30))
    if (
        bool(th.get("enable_similarity_global", True))
        and where != "bigquery"
        and profile.n_series >= 2
        and (
            profile.has_similarity_clusters
            or (
                profile.optimal_similarity_clusters >= 2
                and profile.similarity_silhouette_score >= sim_sil_min
            )
            or bool(diagnostics_summary.get("cold_start_donor_transfer_recommended", False))
        )
    ):
        features_cfg["similarity_cluster_feature"] = True
        features_cfg["similarity_n_clusters"] = int(max(profile.optimal_similarity_clusters, 2))
        sim_added: list[str] = []
        for sim_base in ("lightgbm", "regression_lags"):
            if sim_base in avail:
                sim_var = f"{sim_base}@similarity_global"
                if sim_var not in current_models:
                    current_models.append(sim_var)
                    added_models.append(sim_var)
                    sim_added.append(sim_var)
                    if sim_base == "lightgbm" and tier in ("first_light", "wide_field"):
                        model_params.setdefault(
                            sim_var,
                            {"n_estimators": int(th.get("tree_n_estimators_fast", 55))},
                        )
        mutations.append(
            {
                "action": "inject_similarity_global",
                "domain": "covariates_and_horizon",
                "parameter": "models + features.similarity_cluster_feature",
                "old_value": "similarity_cluster_feature=False",
                "new_value": (
                    f"+{', '.join(sim_added) or 'similarity_global'}, "
                    f"similarity_cluster_feature=True (K={features_cfg['similarity_n_clusters']})"
                ),
                "evidence": (
                    f"optimal_similarity_clusters={profile.optimal_similarity_clusters}, "
                    f"similarity_silhouette_score={profile.similarity_silhouette_score:.2f}, "
                    f"mean_pairwise_similarity={profile.mean_pairwise_similarity:.2f}"
                ),
                "rationale": (
                    "Panel exhibits distinct trajectory clusters; synthesizing "
                    "similarity_cluster_id and injecting @similarity_global peer-context lag "
                    "specialists."
                ),
            }
        )
        if (
            not has_hierarchy
            and profile.n_series >= 4
            and profile.optimal_similarity_clusters >= 2
            and profile.similarity_silhouette_score >= sim_sil_min
        ):
            hierarchy_cfg["similarity_hierarchy"] = True
            hierarchy_cfg["similarity_n_clusters"] = int(profile.optimal_similarity_clusters)
            hierarchy_cfg.setdefault("reconciliation_methods", ["wls_struct", "mint_shrink"])
            mutations.append(
                {
                    "action": "enable_similarity_hierarchy",
                    "domain": "regime_and_specialists",
                    "parameter": "hierarchy.similarity_hierarchy",
                    "old_value": "False",
                    "new_value": f"True (K={profile.optimal_similarity_clusters})",
                    "evidence": (
                        f"optimal_similarity_clusters={profile.optimal_similarity_clusters}, "
                        f"similarity_silhouette_score={profile.similarity_silhouette_score:.2f}"
                    ),
                    "rationale": (
                        "Materializing synthetic __sim_cluster_id__ hierarchy for coherent "
                        "cross-cluster WLS/MinT reconciliation."
                    ),
                }
            )

    # 7. Hierarchical Non-Negative Coherent & Cross-Temporal Specialist Escalation (dgp_08 / dgp_14)
    if has_hierarchy:
        hier_added: list[str] = []
        for h_cand in ("holtwinters", "regression_lags", "xgboost"):
            if h_cand in avail and h_cand not in current_models:
                current_models.append(h_cand)
                added_models.append(h_cand)
                hier_added.append(h_cand)
                if h_cand == "xgboost" and tier in ("first_light", "wide_field"):
                    model_params.setdefault(
                        h_cand, {"n_estimators": int(th.get("tree_n_estimators_fast", 55))}
                    )
        rec_methods = list(select_hierarchy_reconciliation_methods(profile, tier=tier))
        if hierarchy_cfg:
            if profile.horizon >= 7 and profile.median_n_obs >= 28:
                hierarchy_cfg["reconcile_temporal"] = True
                hierarchy_cfg["cross_temporal"] = True
                if "cross_temporal_mint" not in rec_methods:
                    rec_methods.append("cross_temporal_mint")
            hierarchy_cfg["reconciliation_methods"] = rec_methods
        if hier_added:
            strats_h = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "champion" not in strats_h:
                strats_h.append("champion")
            ensemble_cfg["strategies"] = strats_h
            mutations.append(
                {
                    "action": "refine_hierarchical_coherence",
                    "domain": "regime_and_specialists",
                    "parameter": "models + hierarchy.reconciliation_methods",
                    "old_value": f"{len(current_models) - len(hier_added)} base models",
                    "new_value": (
                        f"+{', '.join(hier_added)} (reconciled via {', '.join(rec_methods)})"
                    ),
                    "evidence": (
                        f"hierarchy_id_cols={list(profile.hierarchy_id_cols)}, "
                        f"hierarchy_node_count={profile.hierarchy_node_count or profile.n_series}"
                    ),
                    "rationale": (
                        "Adding triple exponential smoothing and regularized lag models across all "
                        "hierarchy nodes before applying scale-aware coherent reconciliation "
                        f"({', '.join(rec_methods)})."
                    ),
                }
            )
    elif (
        profile.is_compositional_simplex
        and profile.horizon >= 7
        and profile.median_n_obs >= 28
        and where != "bigquery"
        and not bool(hierarchy_cfg.get("reconcile_temporal", False))
    ):
        hierarchy_cfg["reconcile_temporal"] = True
        hierarchy_cfg.setdefault("reconciliation_methods", ["wls_struct"])
        mutations.append(
            {
                "action": "enable_temporal_reconciliation",
                "domain": "regime_and_specialists",
                "parameter": "hierarchy.reconcile_temporal",
                "old_value": "False",
                "new_value": "True (wls_struct)",
                "evidence": f"freq='{profile.freq}', horizon={profile.horizon}",
                "rationale": (
                    "Enables multi-horizon THieF temporal hierarchy reconciliation across "
                    "aggregated calendar horizons."
                ),
            }
        )

    # 8. Probabilistic / Newsvendor Service-Level Quantile Refinement (dgp_10)
    if is_probabilistic_goal:
        prob_added: list[str] = []
        for p_cand in ("holtwinters", "regression_lags", "xgboost"):
            if p_cand in avail and p_cand not in current_models:
                current_models.append(p_cand)
                added_models.append(p_cand)
                prob_added.append(p_cand)
                if p_cand == "xgboost" and tier in ("first_light", "wide_field"):
                    model_params.setdefault(
                        p_cand, {"n_estimators": int(th.get("tree_n_estimators_fast", 55))}
                    )
        old_pf = str(output_cfg.get("point_forecast", "median"))
        if prob_added or old_pf != "auto":
            output_cfg["point_forecast"] = "auto"
            if (
                goal == "service_level"
                and output_cfg.get("target_quantile") is None
                and output_cfg.get("underage_cost") is None
            ):
                output_cfg["underage_cost"] = 9.0
                output_cfg["overage_cost"] = 1.0
            strats_p = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "champion" not in strats_p:
                strats_p.append("champion")
            if n_folds >= 2 and "nnls" not in strats_p:
                strats_p.append("nnls")
            ensemble_cfg["strategies"] = strats_p
            mutations.append(
                {
                    "action": "refine_probabilistic_quantiles",
                    "domain": "regime_and_specialists",
                    "parameter": "models + output.point_forecast",
                    "old_value": f"point_forecast={old_pf}",
                    "new_value": (f"+{', '.join(prob_added) or 'existing'}, point_forecast='auto'"),
                    "evidence": f"goal='{goal}', decision_metric='{decision_metric}'",
                    "rationale": (
                        "Optimizing upper-tail Newsvendor pinball / interval loss via per-cell "
                        "OOF arm calibration (point_forecast='auto') and expanded learners."
                    ),
                }
            )

    # 8.2. Non-Exchangeable Drift -> Adaptive Conformal Inference (ACI / CQR) Escalation
    ks_drift = max(
        float(getattr(profile, "residual_drift_ks_stat", 0.0)),
        float(diagnostics_summary.get("residual_drift_ks_stat", 0.0)),
    )
    cov_drift = bool(diagnostics_summary.get("coverage_drift_detected", False)) or (
        is_probabilistic_goal and ks_drift >= 0.28
    )
    old_cal = str(output_cfg.get("calibration_method", "conformal"))
    if cov_drift and old_cal == "conformal":
        output_cfg["calibration_method"] = "aci_normalized"
        output_cfg.setdefault("aci_gamma", 0.05)
        mutations.append(
            {
                "action": "enable_adaptive_conformal",
                "domain": "regime_and_specialists",
                "parameter": "output.calibration_method",
                "old_value": old_cal,
                "new_value": f"aci_normalized (aci_gamma={output_cfg['aci_gamma']})",
                "evidence": (
                    f"coverage_drift_detected={cov_drift}, residual_drift_ks_stat={ks_drift:.2f}"
                ),
                "rationale": (
                    "Non-exchangeable residual drift detected across backtest folds; escalating "
                    "prediction intervals to Adaptive Conformal Inference (ACI) online tracking."
                ),
            }
        )

    # 8.5. Censored Demand / Stockout Reconstruction Specialist Escalation (dgp_07)
    has_censored = bool(profile.censored_col) or bool(features_cfg.get("censored_col"))
    if has_censored:
        cens_added: list[str] = []
        for c_cand in ("holtwinters", "regression_lags", "xgboost"):
            if c_cand in avail and c_cand not in current_models:
                current_models.append(c_cand)
                added_models.append(c_cand)
                cens_added.append(c_cand)
                if c_cand == "xgboost" and tier in ("first_light", "wide_field"):
                    model_params.setdefault(
                        c_cand, {"n_estimators": int(th.get("tree_n_estimators_fast", 55))}
                    )
        if cens_added:
            strats_c = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            for s_tag in ("champion", "horizon_specialist"):
                if s_tag not in strats_c:
                    strats_c.append(s_tag)
            ensemble_cfg["strategies"] = strats_c
            mutations.append(
                {
                    "action": "refine_censored_demand_models",
                    "domain": "regime_and_specialists",
                    "parameter": "models + ensemble.strategies",
                    "old_value": f"censored_col={features_cfg.get('censored_col')}",
                    "new_value": f"+{', '.join(cens_added)}",
                    "evidence": f"censored_col='{features_cfg.get('censored_col')}'",
                    "rationale": (
                        "Adding triple exponential smoothing, regularized linear lags, and "
                        "gradient boosting over reconstructed uncensored latent demand."
                    ),
                }
            )

    # 8.8. In-Warehouse BigQuery SQL Foundation Escalation (`where == 'bigquery'`)
    if where == "bigquery" and "timesfm" in avail and "timesfm" not in current_models:
        current_models.append("timesfm")
        added_models.append("timesfm")
        ensemble_cfg["enabled"] = True
        strats_bq = list(ensemble_cfg.get("strategies", ["inverse_error", "mean"]))
        for s_tag in ("champion", "horizon_specialist"):
            if s_tag not in strats_bq:
                strats_bq.append(s_tag)
        ensemble_cfg["strategies"] = strats_bq
        mutations.append(
            {
                "action": "escalate_bigquery_foundation",
                "domain": "regime_and_specialists",
                "parameter": "models + ensemble.strategies",
                "old_value": "arima_plus",
                "new_value": "arima_plus, timesfm (with champion + horizon_specialist blending)",
                "evidence": "where='bigquery', Pass 1 evaluated arima_plus baseline",
                "rationale": (
                    "Escalating in-warehouse BigQuery SQL portfolio to include AI.FORECAST "
                    "(TimesFM foundation model) while borrowing Pass 1's ARIMA_PLUS cells."
                ),
            }
        )

    # 9. Residual Autocorrelation / Underfitting -> Escalate Model Expressiveness
    resid_acf1 = float(diagnostics_summary.get("residual_autocorr_lag1", 0.0))
    fva_pct = float(diagnostics_summary.get("fva_vs_naive_pct", 0.0))
    if (
        not mutations
        and (
            resid_acf1 >= float(th.get("resid_acf1_escalate_min", 0.30))
            or fva_pct < float(th.get("fva_escalate_min_pct", 2.0))
        )
        and not (wn_stop and diagnostics_summary.get("white_noise_residuals", False))
    ):
        escalated: list[str] = []
        esc_pool = (
            ("holtwinters", "regression_lags", "catboost", "random_forest", "fft", "autoets")
            if tier in ("first_light", "wide_field")
            else ("catboost", "random_forest", "stl_bagging", "autoets", "tide")
        )
        for cand in esc_pool:
            if cand in avail and cand not in [m.split("@", 1)[0] for m in current_models]:
                spec_cand = f"{cand}@global" if (cand == "tide" and profile.n_series >= 4) else cand
                current_models.append(spec_cand)
                added_models.append(spec_cand)
                escalated.append(spec_cand)
                if tier in ("first_light", "wide_field"):
                    if cand == "catboost":
                        model_params.setdefault(spec_cand, {"iterations": 80})
                    elif cand in ("lightgbm", "xgboost", "random_forest"):
                        model_params.setdefault(spec_cand, {"n_estimators": 80})
                if len(escalated) >= 2:
                    break
        if escalated:
            if profile.horizon >= 7 and profile.median_n_obs >= 28 and where != "bigquery":
                hierarchy_cfg["reconcile_temporal"] = True
            strats_esc = list(ensemble_cfg.get("strategies", ["inverse_error"]))
            if "champion" not in strats_esc:
                strats_esc.append("champion")
            ensemble_cfg["strategies"] = strats_esc
            mutations.append(
                {
                    "action": "escalate_model_diversity",
                    "domain": "regime_and_specialists",
                    "parameter": "models",
                    "old_value": f"{len(current_models) - len(escalated)} models",
                    "new_value": f"+{', '.join(escalated)}",
                    "evidence": f"residual_acf1={resid_acf1:.2f}, fva_vs_naive_pct={fva_pct:.2f}%",
                    "rationale": (
                        "Exploitable autocorrelation remains in Pass 1 residuals; expanding model "
                        "diversity while borrowing completed Pass 1 models."
                    ),
                }
            )

    freq_lags_p2 = _frequency_matched_lags(profile, n_folds=n_folds)
    if freq_lags_p2 is not None:
        for lag_m in ("lightgbm", "xgboost", "catboost", "random_forest", "regression_lags"):
            if any(m.split("@", 1)[0] == lag_m for m in current_models):
                model_params.setdefault(lag_m, {}).setdefault("lags", list(freq_lags_p2))

    if _return_mutations_only:
        return mutations

    return {
        "models": current_models,
        "added_models": added_models,
        "model_params": model_params,
        "features": features_cfg,
        "output": output_cfg,
        "ensemble": ensemble_cfg,
        "backtest": backtest_cfg,
        "hierarchy": hierarchy_cfg,
        "mutations": mutations,
    }

propose_autofocus_synthesis_pass

propose_autofocus_synthesis_pass(
    profile,
    pass1_config_dict,
    branch_outcomes,
    *,
    tier="wide_field",
    where="auto",
    goal="accuracy",
)

Synthesize winning Level-2 Tournament DAG branches into a Level-3 Join & Stacking config.

Combines all feature, output, and model additions from Level-2 branches that improved upon Pass 1's validation score, enables learned stacking (nnls, ridge, champion, horizon_specialist), and optionally enables targeted Optuna HPO on deep_sky/deep_field.

Source code in src/scale_forecasting/auto_policy.py
def propose_autofocus_synthesis_pass(
    profile: PanelAutoProfile,
    pass1_config_dict: dict[str, Any],
    branch_outcomes: Sequence[dict[str, Any]],
    *,
    tier: str = "wide_field",
    where: str = "auto",
    goal: str = "accuracy",
) -> dict[str, Any]:
    """Synthesize winning Level-2 Tournament DAG branches into a Level-3 Join & Stacking config.

    Combines all feature, output, and model additions from Level-2 branches that improved upon
    Pass 1's validation score, enables learned stacking (`nnls`, `ridge`, `champion`,
    `horizon_specialist`), and optionally enables targeted Optuna HPO on `deep_sky`/`deep_field`.
    """
    _ = (profile, where, goal)
    synth_models: list[str] = list(pass1_config_dict.get("models", []))
    synth_features: dict[str, Any] = dict(pass1_config_dict.get("features", {}))
    synth_output: dict[str, Any] = dict(pass1_config_dict.get("output", {}))
    synth_ensemble: dict[str, Any] = dict(pass1_config_dict.get("ensemble", {}))
    synth_backtest: dict[str, Any] = dict(pass1_config_dict.get("backtest", {}))
    synth_hierarchy: dict[str, Any] = dict(pass1_config_dict.get("hierarchy") or {})
    synth_hpo: dict[str, Any] = dict(pass1_config_dict.get("hpo", {}))
    synth_params: dict[str, dict[str, Any]] = {
        k: dict(v) for k, v in dict(pass1_config_dict.get("model_params", {})).items()
    }
    n_folds = int(pass1_config_dict.get("backtest", {}).get("n_folds", 1))

    winning_ids: list[str] = []
    merged_actions: list[str] = []
    added_models: list[str] = []

    for b in branch_outcomes:
        b_id = str(b.get("pass_id", "2"))
        b_score = float(b.get("best_score", float("inf")))
        p1_score = float(b.get("pass1_score", float("inf")))
        # Accept branch if it beat or matched Pass 1 within 0.5%
        if b_score <= p1_score * 1.005:
            winning_ids.append(b_id)
            b_cfg = dict(b.get("config_dict", {}))
            for m in b_cfg.get("models", []):
                if m not in synth_models:
                    synth_models.append(m)
                    added_models.append(m)
            for k, v in dict(b_cfg.get("model_params", {})).items():
                synth_params.setdefault(k, dict(v))
            b_feat = dict(b_cfg.get("features", {}))
            for fk in (
                "future_covariates",
                "exog_lags",
                "monotonic_constraints",
                "holiday_window",
                "transform",
                "simplex_sum",
                "level_shift",
                "outlier_policy",
                "regime_routing",
                "cold_start_transfer",
                "cold_start_matching",
                "similarity_cluster_feature",
                "similarity_n_clusters",
            ):
                if fk in b_feat and b_feat[fk] != pass1_config_dict.get("features", {}).get(fk):
                    synth_features[fk] = b_feat[fk]
            b_bt = dict(b_cfg.get("backtest", {}))
            if "scheme" in b_bt and b_bt["scheme"] != pass1_config_dict.get("backtest", {}).get(
                "scheme"
            ):
                synth_backtest["scheme"] = b_bt["scheme"]
            b_hier = dict(b_cfg.get("hierarchy") or {})
            if "reconciliation_methods" in b_hier:
                synth_hierarchy["reconciliation_methods"] = list(b_hier["reconciliation_methods"])
            for hk in (
                "reconcile_temporal",
                "temporal_aggregations",
                "cross_temporal",
                "spatial_temporal_weight",
                "similarity_hierarchy",
                "similarity_n_clusters",
            ):
                if hk in b_hier and b_hier[hk] != (pass1_config_dict.get("hierarchy") or {}).get(
                    hk
                ):
                    synth_hierarchy[hk] = b_hier[hk]
            b_out = dict(b_cfg.get("output", {}))
            for ok in ("point_forecast", "target_quantile", "calibration_method", "aci_gamma"):
                if ok in b_out and b_out[ok] is not None:
                    synth_output[ok] = b_out[ok]
            for s in b_cfg.get("ensemble", {}).get("strategies", []):
                if s not in synth_ensemble.get("strategies", []):
                    synth_ensemble.setdefault("strategies", []).append(s)
            for mut_act in b.get("mutations_applied", ()):
                if mut_act not in merged_actions:
                    merged_actions.append(str(mut_act))

    strats = list(synth_ensemble.get("strategies", ["inverse_error"]))
    for s_stack in ("champion", "horizon_specialist"):
        if s_stack not in strats:
            strats.append(s_stack)
    if n_folds >= 2:
        for s_learned in ("nnls", "ridge"):
            if s_learned not in strats:
                strats.append(s_learned)
    synth_ensemble["strategies"] = strats
    synth_ensemble["enabled"] = len(synth_models) >= 2

    if tier in ("deep_sky", "deep_field"):
        synth_hpo["enabled"] = True
        synth_hpo["n_trials"] = max(int(synth_hpo.get("n_trials", 6)), 6)

    parent_ids = (
        tuple(winning_ids)
        if winning_ids
        else tuple(str(b.get("pass_id", "2")) for b in branch_outcomes)
    )
    mutations = [
        {
            "action": "synthesize_winning_dag_branches",
            "domain": "synthesis",
            "parameter": "models + features + ensemble.strategies",
            "old_value": f"branches={[b.get('pass_id') for b in branch_outcomes]}",
            "new_value": f"merged={list(parent_ids)}, strategies={strats}",
            "evidence": f"winning_branches={list(parent_ids)}, actions={merged_actions}",
            "rationale": (
                "Synthesizes all non-degrading Level-2 hypothesis branches into a unified "
                "model portfolio with learned stacking and cell borrowing across all branches."
            ),
        }
    ]
    return {
        "pass_id": "3",
        "parent_pass_ids": parent_ids,
        "branch_hypothesis": "Level-3 Tournament Synthesis & Learned Stacking",
        "models": synth_models,
        "added_models": added_models,
        "model_params": synth_params,
        "features": synth_features,
        "output": synth_output,
        "ensemble": synth_ensemble,
        "backtest": synth_backtest,
        "hierarchy": synth_hierarchy or None,
        "hpo": synth_hpo,
        "mutations": mutations,
    }

select_default_baselines

select_default_baselines(
    profile,
    *,
    where="auto",
    available_models=None,
    candidate_models=None,
    selected_models=None,
    user_baselines="auto",
)

Build the 4-Anchor Opinionated Baseline Ladder (baselines='auto') or resolve explicit user-pinned baselines.

Returns a list of baseline descriptor dicts with keys model_type (alias model), baseline_role (alias role), and description: 1. naive_anchor: naive_seasonal (plus naive_mean on intermittent panels) 2. plain_univariate_stat: theta / arima_plus@univariate / croston@classic 3. zero_shot_foundation: chronos_bolt / timesfm_torch@univariate / chronos2@univariate / timesfm@univariate (when available in the execution environment) 4. same_model_univariate: <lead_model>@univariate when exogenous covariates are present

Source code in src/scale_forecasting/auto_policy.py
def select_default_baselines(
    profile: PanelAutoProfile,
    *,
    where: str = "auto",
    available_models: Sequence[str] | None = None,
    candidate_models: Sequence[str] | None = None,
    selected_models: Sequence[str] | None = None,
    user_baselines: str | Sequence[str] | None = "auto",
) -> list[dict[str, str]]:
    """Build the 4-Anchor Opinionated Baseline Ladder (`baselines='auto'`) or resolve explicit
    user-pinned baselines.

    Returns a list of baseline descriptor dicts with keys `model_type` (alias `model`),
    `baseline_role` (alias `role`), and `description`:
    1. `naive_anchor`: `naive_seasonal` (plus `naive_mean` on intermittent panels)
    2. `plain_univariate_stat`: `theta` / `arima_plus@univariate` / `croston@classic`
    3. `zero_shot_foundation`: `chronos_bolt` / `timesfm_torch@univariate` / `chronos2@univariate`
       / `timesfm@univariate` (when available in the execution environment)
    4. `same_model_univariate`: `<lead_model>@univariate` when exogenous covariates are present
    """

    def _entry(model_type: str, role: str, description: str) -> dict[str, str]:
        return {
            "model_type": model_type,
            "baseline_role": role,
            "model": model_type,
            "role": role,
            "description": description,
        }

    if user_baselines is not None and user_baselines != "auto":
        raw_list = [user_baselines] if isinstance(user_baselines, str) else list(user_baselines)
        entries: list[dict[str, str]] = [
            _entry(
                str(b),
                "user_pinned_baseline",
                f"User-selected baseline anchor ({b}).",
            )
            for b in dict.fromkeys(str(x) for x in raw_list if str(x))
        ]
        if not any(e["model_type"] == "naive_seasonal" for e in entries):
            entries.insert(
                0,
                _entry(
                    "naive_seasonal",
                    "naive_anchor",
                    "Zero-skill seasonal anchor (repeats last seasonal cycle).",
                ),
            )
        return entries

    avail = set(available_models or ())
    cands = list(selected_models if selected_models is not None else (candidate_models or ()))
    has_covs = bool(profile.future_covariates or profile.past_covariates)
    is_intermittent = profile.zero_fraction >= 0.20 or profile.dominant_regime in (
        "intermittent",
        "lumpy",
    )

    ladder: list[dict[str, str]] = [
        _entry(
            "naive_seasonal",
            "naive_anchor",
            "Zero-skill seasonal anchor (repeats last seasonal cycle).",
        )
    ]
    if is_intermittent and ("naive_mean" in avail or "naive_mean" in cands):
        ladder.append(
            _entry(
                "naive_mean",
                "naive_anchor",
                "Unbiased historical mean anchor for intermittent series.",
            )
        )

    # Slot 2: Plain Univariate Statistical Anchor
    if where == "bigquery":
        stat_m = "arima_plus@univariate" if has_covs else "arima_plus"
        ladder.append(
            _entry(
                stat_m,
                "plain_univariate_stat",
                "Plain univariate BigQuery ML ARIMA_PLUS using only target history y.",
            )
        )
    elif is_intermittent and ("croston" in avail or any(m.startswith("croston") for m in cands)):
        ladder.append(
            _entry(
                "croston@classic",
                "plain_univariate_stat",
                "Plain univariate Classic Croston intermittent baseline.",
            )
        )
    else:
        stat_m = "theta"
        ladder.append(
            _entry(
                stat_m,
                "plain_univariate_stat",
                "Plain univariate Theta exponential smoothing baseline using only y.",
            )
        )

    # Slot 3: Zero-Shot Foundation Model Baseline
    if where == "bigquery" and ("timesfm" in avail or any(m.startswith("timesfm") for m in cands)):
        fm_bq = "timesfm@univariate" if has_covs else "timesfm"
        ladder.append(
            _entry(
                fm_bq,
                "zero_shot_foundation",
                "Zero-shot univariate BigQuery AI.FORECAST (TimesFM) foundation baseline.",
            )
        )
    else:
        for fm_cand, fm_uni in (
            ("chronos_bolt", "chronos_bolt"),
            ("timesfm_torch", "timesfm_torch@univariate" if has_covs else "timesfm_torch"),
            ("chronos2", "chronos2@univariate" if has_covs else "chronos2"),
        ):
            if fm_cand in avail or any(m.split("@", 1)[0] == fm_cand for m in cands):
                ladder.append(
                    _entry(
                        fm_uni,
                        "zero_shot_foundation",
                        f"Zero-shot pretrained foundation baseline ({fm_uni}).",
                    )
                )
                break

    # Slot 4: Same-Model Plain Univariate Twin when covariates exist
    if has_covs:
        for cov_base in (
            "lightgbm",
            "regression_lags",
            "xgboost",
            "chronos2",
            "timesfm_torch",
            "arima_plus",
            "timesfm",
        ):
            if any(m.split("@", 1)[0] == cov_base for m in cands) or cov_base in avail:
                uni_twin = f"{cov_base}@univariate"
                if not any(b["model_type"] == uni_twin for b in ladder):
                    ladder.append(
                        _entry(
                            uni_twin,
                            "same_model_univariate",
                            (
                                f"Plain univariate twin of {cov_base} (strips all covariates to "
                                "measure exact exogenous covariate lift)."
                            ),
                        )
                    )
                    break

    return ladder

select_hierarchy_reconciliation_methods

select_hierarchy_reconciliation_methods(
    profile, *, tier="wide_field"
)

Select hierarchy reconciliation methods matched to node count ($N_{\text{nodes}}$ vs. $T$) and leaf sparsity (zero_fraction).

Source code in src/scale_forecasting/auto_policy.py
def select_hierarchy_reconciliation_methods(
    profile: PanelAutoProfile,
    *,
    tier: str = "wide_field",
) -> list[str]:
    """Select hierarchy reconciliation methods matched to node count ($N_{\\text{nodes}}$ vs. $T$)
    and leaf sparsity (`zero_fraction`).
    """
    n_nodes = max(profile.hierarchy_node_count, profile.n_series)
    t_obs = max(1, profile.median_n_obs)
    is_sparse_leaves = profile.zero_fraction >= 0.30 or profile.dominant_regime in (
        "intermittent",
        "lumpy",
    )

    if n_nodes > 500:
        # Large enterprise tree: O(N) diagonal & structural methods avoid O(N^3) dense covariance
        methods = ["wls_var", "wls_struct", "bottom_up"]
    elif n_nodes > 75 or n_nodes > t_obs:
        # Medium tree (N > 75 or N > T): shrinkage / diagonal WLS + non-negative projection
        primary = "mint_nonneg" if profile.non_negative else "mint_shrink"
        methods = [primary, "wls_var", "wls_struct", "bottom_up"]
    else:
        # Compact tree (N <= 75 and T >= N)
        primary = "mint_nonneg" if profile.non_negative else "mint_shrink"
        if tier in ("deep_sky", "deep_field"):
            methods = [primary, "mint_shrink", "wls_var", "bottom_up"]
        else:
            methods = [primary, "bottom_up"]

    if is_sparse_leaves and "top_down" not in methods:
        methods.append("top_down")
    return list(dict.fromkeys(methods))

select_tier_models_and_features

select_tier_models_and_features(
    profile,
    *,
    tier="wide_field",
    where="auto",
    goal="accuracy",
    allowed_families=None,
    available_models=None,
)

Compile initial Pass 1 model, feature, backtest, and ensemble choices from profile.

Calibrated via Mode A AlphaEvolve (gemini-3.8-flash + gemini-4-argon) over the canonical DGP benchmarks to maximize Forecast Value Added (FVA), covariate signal recovery, interval calibration, and wall-clock efficiency across all 5 n_series scale regimes.

Source code in src/scale_forecasting/auto_policy.py
 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
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
def select_tier_models_and_features(
    profile: PanelAutoProfile,
    *,
    tier: str = "wide_field",
    where: str = "auto",
    goal: str = "accuracy",
    allowed_families: Sequence[str] | None = None,
    available_models: Sequence[str] | None = None,
) -> dict[str, Any]:
    """Compile initial Pass 1 model, feature, backtest, and ensemble choices from `profile`.

    Calibrated via Mode A AlphaEvolve (`gemini-3.8-flash` + `gemini-4-argon`) over the canonical
    DGP benchmarks to maximize Forecast Value Added (FVA), covariate signal recovery, interval
    calibration, and wall-clock efficiency across all 5 `n_series` scale regimes.
    """
    avail = set(
        available_models
        if available_models is not None
        else (
            "naive_seasonal",
            "naive_mean",
            "naive_drift",
            "naive_moving_average",
            "theta",
            "holtwinters",
            "stl_bagging",
            "croston",
            "fft",
            "regression_lags",
            "sarimax",
            "autoets",
            "lightgbm",
            "xgboost",
            "catboost",
            "random_forest",
            "chronos_bolt",
            "chronos2",
            "timesfm_torch",
            "tide",
            "tsmixer",
            "patchtst",
            "tft",
            "vertex_tide",
            "vertex_tft",
            "vertex_l2l",
            "vertex_seq2seq",
            "arima_plus",
            "timesfm",
        )
    )
    allowed_fams = (
        set(allowed_families)
        if allowed_families is not None
        else {"statistical", "ml", "deep_learning", "automl", "native"}
    )

    rationales: list[dict[str, str]] = []
    models: list[str] = []
    th = evolved_policy_thresholds()
    scale_regime = profile.scale_regime
    regime_meta = SCALE_REGIMES[scale_regime]
    rationales.append(
        {
            "category": "scale_regime",
            "parameter": "scale_regime",
            "value": f"{scale_regime} ({regime_meta['title']})",
            "evidence": f"n_series={profile.n_series}, n_rows={profile.n_rows}",
            "rationale": str(regime_meta["strategy"]),
        }
    )

    def _add_model(m: str, family: str, reason: str, evidence: str) -> None:
        base = m.split("@", 1)[0]
        if family in allowed_fams and base in avail and m not in models:
            models.append(m)
            rationales.append(
                {
                    "category": "models",
                    "parameter": m,
                    "value": f"include ({family})",
                    "evidence": evidence,
                    "rationale": reason,
                }
            )

    # 1. Always anchor with a fast seasonal benchmark for FVA & Diebold-Mariano testing
    _add_model(
        "naive_seasonal",
        "statistical",
        "Establishes the zero-skill seasonal benchmark for Forecast Value Added and DM tests.",
        f"freq={profile.freq}, median_acf={profile.median_acf_season:.2f}",
    )

    is_intermittent_heavy = (
        profile.dominant_regime in ("intermittent", "lumpy")
        or profile.zero_fraction >= 0.20
        or profile.median_adi >= 1.32
        or (
            profile.regime_shares.get("intermittent", 0.0) + profile.regime_shares.get("lumpy", 0.0)
        )
        >= float(th.get("intermittent_share_min", 0.25))
    )
    has_cold_start = (
        profile.dominant_regime == "cold_start"
        or profile.regime_shares.get("cold_start", 0.0) > 0.05
        or profile.min_n_obs < max(28, 2 * profile.horizon)
    )
    has_covs = bool(profile.future_covariates or profile.past_covariates)
    skip_slow_local_stat = (
        where == "local" and scale_regime in ("medium", "large", "hyperscale")
    ) or (scale_regime in ("large", "hyperscale"))
    allow_local_foundation = where != "local" or profile.n_series <= 200

    # 2. Tier-progressive & scale-aware model selection
    if where == "bigquery":
        _add_model(
            "arima_plus",
            "native",
            "In-warehouse BigQuery ML ARIMA_PLUS with automatic seasonality and holiday detection.",
            f"where='bigquery', fut_covs={len(profile.future_covariates)}",
        )
        if has_covs and tier != "first_light":
            _add_model(
                "arima_plus@univariate",
                "native",
                "Plain univariate ARIMA_PLUS twin to measure exact exogenous covariate lift.",
                f"fut_covs={len(profile.future_covariates)}",
            )
        if tier != "first_light":
            _add_model(
                "timesfm",
                "native",
                "In-warehouse BigQuery AI.FORECAST (TimesFM zero-shot foundation model).",
                f"tier='{tier}', where='bigquery'",
            )
            if has_covs and tier in ("deep_sky", "deep_field"):
                _add_model(
                    "timesfm@univariate",
                    "native",
                    "Zero-shot univariate TimesFM baseline to isolate multivariate lift.",
                    f"tier='{tier}', fut_covs={len(profile.future_covariates)}",
                )
    elif tier == "first_light":
        _add_model(
            "theta",
            "statistical",
            "Fast M3-winning exponential smoothing with drift (~0.14s/cell).",
            f"dominant_regime={profile.dominant_regime}",
        )
        if is_intermittent_heavy:
            _add_model(
                "croston@tsb",
                "statistical",
                "Teunter-Syntetos-Babai intermittent demand estimator handles zero-heavy series.",
                f"zero_fraction={profile.zero_fraction:.2%}, ADI={profile.median_adi:.2f}",
            )
        _add_model(
            "lightgbm",
            "ml",
            "Fast gradient boosted decision trees capturing lags and covariates.",
            f"n_series={profile.n_series}, covariates={len(profile.future_covariates)}",
        )
        if bool(th.get("first_light_include_regression_lags", False)) and (
            profile.future_covariates or abs(profile.end_to_start_ratio - 1.0) >= 0.25
        ):
            _add_model(
                "regression_lags",
                "ml",
                "Fast ridge lag regression for linear trend and exogenous elasticity.",
                f"fut_covs={len(profile.future_covariates)}, "
                f"growth={profile.end_to_start_ratio:.2f}",
            )
    elif tier == "wide_field":
        _add_model(
            "theta",
            "statistical",
            "Robust trend + seasonal statistical baseline.",
            f"median_n_obs={profile.median_n_obs}",
        )
        if scale_regime != "hyperscale":
            _add_model(
                "holtwinters",
                "statistical",
                "Captures damped trend and seasonal harmonics cleanly.",
                f"median_acf={profile.median_acf_season:.2f}",
            )
        _add_model(
            "fft",
            "statistical",
            "Fast Fourier harmonic extrapolation for periodic seasonal cycles.",
            f"dominant_regime={profile.dominant_regime}",
        )
        if is_intermittent_heavy:
            _add_model(
                "naive_mean",
                "statistical",
                "Unbiased level anchor for high-sparsity intermittent demand.",
                f"zero_fraction={profile.zero_fraction:.2%}",
            )
            _add_model(
                "croston@classic",
                "statistical",
                "Classic Croston separate size/interval exponential smoothing.",
                f"ADI={profile.median_adi:.2f}",
            )
            _add_model(
                "croston@sba",
                "statistical",
                "Syntetos-Boylan bias-corrected intermittent demand estimator.",
                f"ADI={profile.median_adi:.2f}, CV2={profile.median_cv2:.2f}",
            )
            _add_model(
                "croston@tsb",
                "statistical",
                "TSB probability-updating intermittent estimator for obsolescence/lumpy SKUs.",
                f"zero_fraction={profile.zero_fraction:.2%}",
            )
        _add_model(
            "lightgbm",
            "ml",
            "GBDT learner capturing nonlinear lag and exogenous patterns.",
            f"n_series={profile.n_series}, fut_covs={len(profile.future_covariates)}",
        )
        _add_model(
            "xgboost",
            "ml",
            "Complementary regularized gradient boosted trees for diverse ensemble blending.",
            f"n_series={profile.n_series}",
        )
        _add_model(
            "regression_lags",
            "ml",
            "Fast ridge lag regression providing linear extrapolation and attribution weights.",
            f"end_to_start_ratio={profile.end_to_start_ratio:.2f}",
        )
        if "chronos_bolt" in avail and allow_local_foundation:
            cb_spec = "chronos_bolt@global" if profile.n_series >= 15 else "chronos_bolt"
            _add_model(
                cb_spec,
                "deep_learning",
                "Zero-shot pretrained foundation baseline excels on cold-start and complex series.",
                f"has_cold_start={has_cold_start}, scale_regime={scale_regime}",
            )
    elif tier in ("deep_sky", "deep_field"):
        fast_stats = (
            ("theta", "Fast statistical baseline for trend + seasonality."),
            ("holtwinters", "Triple exponential smoothing for seasonal series."),
            ("fft", "Fast Fourier harmonic decomposition."),
        )
        for stat_m, desc in fast_stats:
            if scale_regime == "hyperscale" and stat_m == "holtwinters":
                continue
            _add_model(stat_m, "statistical", desc, f"tier={tier}")

        if not skip_slow_local_stat:
            for slow_m, desc in (
                ("autoets", "State-space Error-Trend-Seasonal automatic selection."),
                ("stl_bagging", "Bagged STL decomposition for variance reduction."),
            ):
                _add_model(slow_m, "statistical", desc, f"tier={tier}, scale_regime={scale_regime}")
        else:
            rationales.append(
                {
                    "category": "scale_guardrail",
                    "parameter": "autoets, stl_bagging",
                    "value": "pruned_for_scale",
                    "evidence": f"n_series={profile.n_series}, scale_regime='{scale_regime}'",
                    "rationale": (
                        "Skipped slow O(T^2) per-series state-space fits at medium/large scale in "
                        "favor of vectorized statistical and @global pooled learners."
                    ),
                }
            )
        if is_intermittent_heavy:
            _add_model("naive_mean", "statistical", "Level anchor for sparse demand.", "sparse")
            _add_model("croston@classic", "statistical", "Classic Croston estimator.", "sparse")
            _add_model("croston@sba", "statistical", "SBA intermittent estimator.", "sparse")
            _add_model("croston@tsb", "statistical", "TSB intermittent estimator.", "sparse")
        for ml_m, desc in (
            ("lightgbm", "Gradient boosted trees across lags and covariates."),
            ("xgboost", "Regularized gradient boosted trees across lags and covariates."),
            ("catboost", "Symmetric oblivious trees resistant to covariate overfitting."),
            ("regression_lags", "Penalized ridge lag model for clean elasticity."),
        ):
            _add_model(ml_m, "ml", desc, f"tier={tier}")
        for dl_m, desc in (
            ("tide", "Time-series Dense Encoder (TiDE) for global nonlinear covariate projection."),
            ("tsmixer", "All-MLP time- and feature-mixing neural architecture."),
            ("chronos_bolt", "Zero-shot univariate foundation model baseline."),
        ):
            if dl_m in avail and (allow_local_foundation or dl_m in ("tide", "tsmixer")):
                # On micro panels (<15 series) with low cross-series correlation, avoid overfitting
                # trained global neural nets on tiny sample sizes unless tier == deep_field
                if (
                    dl_m in ("tide", "tsmixer")
                    and scale_regime == "micro"
                    and tier != "deep_field"
                    and profile.cross_series_corr < 0.45
                    and where == "local"
                ):
                    spec_dl = f"{dl_m}@global" if profile.n_series >= 4 else dl_m
                else:
                    spec_dl = f"{dl_m}@global" if profile.n_series >= 4 else dl_m
                _add_model(spec_dl, "deep_learning", desc, f"tier={tier}")
        if tier == "deep_field":
            for extra_dl in ("patchtst", "tft", "chronos2", "timesfm_torch"):
                if extra_dl in avail and allow_local_foundation:
                    spec_ex = f"{extra_dl}@global" if profile.n_series >= 4 else extra_dl
                    _add_model(
                        spec_ex,
                        "deep_learning",
                        f"Deep Field neural/foundation specialist ({extra_dl}).",
                        "tier=deep_field",
                    )
                    if has_covs and extra_dl in ("chronos2", "timesfm_torch"):
                        uni_fm = f"{extra_dl}@univariate"
                        _add_model(
                            uni_fm,
                            "deep_learning",
                            f"Zero-shot univariate foundation baseline for {extra_dl}.",
                            f"fut_covs={len(profile.future_covariates)}",
                        )
            if "automl" in allowed_fams and (
                (allowed_families is not None and "automl" in allowed_families)
                or (where == "cloud_all" and profile.n_series >= 100)
            ):
                _add_model(
                    "vertex_tide",
                    "automl",
                    "Managed Vertex AI AutoML TiDE trainer for large fleet deep_field runs.",
                    f"n_series={profile.n_series}, where={where}",
                )
            if where in ("auto", "bigquery", "cloud_all") and not profile.source_table.startswith(
                "dataframe"
            ):
                _add_model(
                    "arima_plus",
                    "native",
                    "In-warehouse BigQuery ML ARIMA_PLUS running in parallel with Python families.",
                    "where=cloud",
                )

    if not models:
        models = ["naive_seasonal", "theta"]

    # 2.5. Data Grid Hygiene: Pre-Launch Leading Zeros & Timestamp Gaps
    trim_leading_zeros = bool(profile.leading_zero_share >= 0.10)
    if trim_leading_zeros:
        rationales.append(
            {
                "category": "data",
                "parameter": "data.trim_leading_zeros",
                "value": "True",
                "evidence": f"leading_zero_share={profile.leading_zero_share:.1%}",
                "rationale": (
                    "Trims pre-launch leading zero runs before each series' first active sale so "
                    "pre-launch zeros do not distort trend or intermittency estimates."
                ),
            }
        )

    grid_policy = (
        ("fill_zero" if (is_intermittent_heavy or profile.integer_valued) else "linear")
        if profile.missing_date_gap_share > 0.0
        else "strict"
    )
    if grid_policy != "strict":
        rationales.append(
            {
                "category": "data",
                "parameter": "data.grid_policy",
                "value": grid_policy,
                "evidence": f"missing_date_gap_share={profile.missing_date_gap_share:.1%}",
                "rationale": (
                    f"Internal timestamp gaps detected across {profile.missing_date_gap_share:.1%} "
                    f"of series; setting grid_policy='{grid_policy}' to regularize the date index."
                ),
            }
        )

    # 3. Target Transformation (Box-Cox / Log1p / Compositional Simplex)
    simplex_sum: float | None = None
    if profile.is_compositional_simplex:
        simplex_sum = round(float(profile.simplex_total or 1.0), 4)
        rationales.append(
            {
                "category": "features",
                "parameter": "features.simplex_sum",
                "value": str(simplex_sum),
                "evidence": (
                    f"is_compositional_simplex=True, simplex_total={simplex_sum}, "
                    f"n_series={profile.n_series}"
                ),
                "rationale": (
                    "Series form a constant-sum compositional simplex across timestamps; "
                    "enforces exact simplex closure and Aitchison log-ratio variants."
                ),
            }
        )
        if where != "bigquery":
            _add_model(
                "theta@transform_ilr",
                "statistical",
                "Isometric log-ratio (ILR) compositional simplex transform on Theta.",
                f"simplex_total={simplex_sum}",
            )
            if tier != "first_light":
                _add_model(
                    "regression_lags@transform_clr",
                    "ml",
                    "Centered log-ratio (CLR) compositional simplex transform on ridge lags.",
                    f"simplex_total={simplex_sum}",
                )

    use_log1p = (
        not profile.is_compositional_simplex
        and tier != "first_light"
        and profile.non_negative
        and not profile.integer_valued
        and profile.level_vol_corr >= float(th.get("log1p_level_vol_corr_min", 0.68))
        and profile.end_to_start_ratio >= float(th.get("log1p_growth_ratio_min", 1.55))
    )
    target_transform = "log1p" if use_log1p else "none"
    if use_log1p:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.target_transform",
                "value": "log1p",
                "evidence": (
                    f"level_vol_corr={profile.level_vol_corr:.2f}, "
                    f"growth_ratio={profile.end_to_start_ratio:.2f}"
                ),
                "rationale": (
                    "Variance scales multiplicatively with series level; log1p stabilizes "
                    "variance and prevents downward linear extrapolation bias."
                ),
            }
        )

    # 4. Structural Breaks, Outlier Scrubbing & Calendar/Fourier Harmonics
    level_shift = tier != "first_light" and profile.structural_break_share >= float(
        th.get("structural_break_share_min", 0.20)
    )
    if level_shift:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.level_shift",
                "value": "True",
                "evidence": f"structural_break_share={profile.structural_break_share:.1%}",
                "rationale": (
                    "Binary-segmentation detected step-change level shifts in >=20% of series; "
                    "adding step indicators prevents historical pre-break levels from biasing fits."
                ),
            }
        )

    outlier_policy = (
        "stl_resid"
        if (
            tier != "first_light"
            and profile.outlier_spike_share >= float(th.get("outlier_spike_share_min", 0.15))
        )
        else "none"
    )
    if outlier_policy != "none":
        rationales.append(
            {
                "category": "features",
                "parameter": "features.outlier_policy",
                "value": outlier_policy,
                "evidence": f"outlier_spike_share={profile.outlier_spike_share:.1%}",
                "rationale": (
                    "Isolated >4.5-MAD historical spikes detected; STL-residual scrubbing "
                    "prevents extreme one-off anomalies from distorting trend and lag weights."
                ),
            }
        )

    trading_days = bool(
        profile.freq in ("MS", "ME", "M", "QS", "QE", "Q") and profile.median_n_obs >= 24
    )
    if trading_days:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.trading_days",
                "value": "True",
                "evidence": f"freq='{profile.freq}', median_n_obs={profile.median_n_obs}",
                "rationale": (
                    "Monthly/quarterly aggregation benefits from X-13 weekday-vs-weekend trading "
                    "day counts per calendar period."
                ),
            }
        )

    f_norm = str(profile.freq).strip().upper()
    fourier = bool(
        (
            tier in ("deep_sky", "deep_field")
            and profile.median_acf_season >= 0.40
            and profile.median_n_obs >= 2 * max(7, profile.horizon)
        )
        or (tier != "first_light" and f_norm in ("H", "1H", "BH") and profile.median_n_obs >= 336)
    )
    if fourier:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.fourier",
                "value": "True",
                "evidence": (
                    f"freq='{profile.freq}', median_acf_season={profile.median_acf_season:.2f}, "
                    f"tier='{tier}'"
                ),
                "rationale": (
                    "Strong periodic autocorrelation or sub-daily multi-seasonality warrants "
                    "harmonic sine/cosine Fourier terms for tree and linear lag learners."
                ),
            }
        )

    # 5. Stockout Censoring Imputation
    censored_col = profile.censored_col
    if censored_col:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.censored_col",
                "value": censored_col,
                "evidence": f"censored_col='{censored_col}' present in panel",
                "rationale": (
                    "Enables fold-safe censored demand imputation so historical stockout dates "
                    "are reconstructed to latent demand before fitting."
                ),
            }
        )

    # 6. SBC Demand Regime Routing & Short-Series Handling
    regime_routing = is_intermittent_heavy or (
        len([s for s in profile.regime_shares.values() if s >= 0.15]) >= 2
        and (is_intermittent_heavy or has_cold_start)
    )
    if regime_routing:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.regime_routing",
                "value": "True",
                "evidence": f"regimes={profile.regime_shares}",
                "rationale": (
                    "Panel mixes heterogeneous Syntetos-Boylan-Croston demand regimes; routing "
                    "prevents smooth tree/ARIMA models from overfitting sparse/cold-start SKUs."
                ),
            }
        )
    if has_cold_start:
        rationales.append(
            {
                "category": "cold_start_transfer",
                "parameter": "cold_start_donor_transfer",
                "value": f"donor_similarity={profile.cold_start_donor_similarity:.2f}",
                "evidence": (
                    f"cold_start_share={profile.regime_shares.get('cold_start', 0.0):.1%}, "
                    f"min_n_obs={profile.min_n_obs}"
                ),
                "rationale": (
                    "Short-history cold-start series detected; analog donor prior transfer and "
                    "SBC regime routing blend mature donor seasonal profiles with empirical-Bayes "
                    "shrinkage."
                ),
            }
        )

    # 7. Physical Output Constraints & Goal Alignment
    floor: float | None = 0.0 if profile.non_negative else None
    if floor is not None:
        rationales.append(
            {
                "category": "output",
                "parameter": "output.floor",
                "value": "0.0",
                "evidence": "min(y) >= 0.0 across 100% of historical observations",
                "rationale": "Enforces physical non-negativity on point forecasts and bounds.",
            }
        )

    integer_rounding = (
        "cumulative_round"
        if (profile.integer_valued and is_intermittent_heavy)
        else ("round" if profile.integer_valued else "none")
    )
    if integer_rounding != "none":
        rationales.append(
            {
                "category": "output",
                "parameter": "output.integer_rounding",
                "value": integer_rounding,
                "evidence": f"integer_valued=True, intermittent={is_intermittent_heavy}",
                "rationale": (
                    "Preserves integer count semantics while cumulative_round prevents "
                    "fractional intermittent demand from rounding down to zero every day."
                ),
            }
        )

    underage_cost: float | None = None
    overage_cost: float | None = None
    target_quantile: float | None = None
    if goal == "service_level":
        decision_metric = "pinball"
        quantiles = [0.1, 0.5, 0.9, 0.95]
        underage_cost = 9.0
        overage_cost = 1.0
    elif goal == "probabilistic":
        decision_metric = "interval_score"
        quantiles = [0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95]
    else:
        decision_metric = "mase" if is_intermittent_heavy else "wape"
        quantiles = [0.1, 0.5, 0.9]

    rationales.append(
        {
            "category": "backtest",
            "parameter": "backtest.decision_metric",
            "value": decision_metric,
            "evidence": f"goal='{goal}', intermittent={is_intermittent_heavy}",
            "rationale": (
                f"Optimizes model selection and ensemble weights for {decision_metric.upper()} "
                f"under goal='{goal}'."
            ),
        }
    )

    # 8. Backtest Folds, Ablations & Ensembling
    max_feasible_folds = max(
        1, min(3, (profile.median_n_obs - profile.horizon - 10) // max(1, profile.horizon))
    )
    if scale_regime == "hyperscale":
        n_folds = 1 if tier in ("first_light", "wide_field") else min(max_feasible_folds, 2)
    else:
        n_folds = (
            1
            if tier == "first_light"
            else min(max_feasible_folds, 2 if tier == "wide_field" else 3)
        )

    include_univariate_baselines = has_covs and tier != "first_light"
    ablation_modes = (
        ["univariate", "local_univariate"]
        if (has_covs and tier in ("deep_sky", "deep_field"))
        else []
    )

    if tier == "first_light":
        _valid_strats = {
            "mean",
            "median",
            "inverse_error",
            "champion",
            "horizon_specialist",
            "nnls",
            "ridge",
            "xgb",
        }
        raw_strats = list(th.get("first_light_ensemble_strategies", ["inverse_error", "mean"]))
        ensemble_strategies = [s for s in raw_strats if s in _valid_strats] or [
            "inverse_error",
            "mean",
        ]
        sel_cand = str(th.get("first_light_selection_rule", "best_single"))
        selection_rule = (
            sel_cand if sel_cand in {"best_single", "best_ensemble", "champion"} else "best_single"
        )
    elif tier == "wide_field":
        ensemble_strategies = (
            ["inverse_error", "nnls", "ridge"] if n_folds >= 2 else ["inverse_error", "mean"]
        )
        selection_rule = "champion"
    else:
        ensemble_strategies = ["inverse_error", "nnls", "ridge"]
        selection_rule = "champion"

    ensemble_top_k: int | None = (
        3
        if scale_regime == "hyperscale"
        else (5 if (len(models) >= 7 or scale_regime == "large") else None)
    )
    parsimony_margin = 0.005

    hpo_enabled = tier in ("deep_sky", "deep_field") and scale_regime != "hyperscale"
    hpo_trials = 6 if tier == "deep_sky" else (12 if tier == "deep_field" else 0)
    hpo_granularity = (
        "per_series" if (scale_regime == "micro" and tier == "deep_field") else "fleetwide"
    )

    n_est_fast = int(th.get("tree_n_estimators_fast", 80))
    model_params: dict[str, dict[str, Any]] = {}
    if profile.median_n_obs <= 365 and tier in ("first_light", "wide_field"):
        for tree_m in ("lightgbm", "xgboost"):
            if any(m.split("@", 1)[0] == tree_m for m in models):
                model_params[tree_m] = {"n_estimators": n_est_fast}

    freq_lags = _frequency_matched_lags(profile, n_folds=n_folds)
    if freq_lags is not None:
        lag_models_present: list[str] = []
        for lag_m in ("lightgbm", "xgboost", "catboost", "random_forest", "regression_lags"):
            if any(m.split("@", 1)[0] == lag_m for m in models):
                model_params.setdefault(lag_m, {})["lags"] = list(freq_lags)
                lag_models_present.append(lag_m)
        if lag_models_present:
            rationales.append(
                {
                    "category": "models",
                    "parameter": "model_params.*.lags",
                    "value": str(freq_lags),
                    "evidence": f"freq='{profile.freq}', min_n_obs={profile.min_n_obs}",
                    "rationale": (
                        f"Configured frequency-matched target lags {freq_lags} across "
                        f"{', '.join(lag_models_present)} to align lag depths with "
                        f"'{profile.freq}' seasonality and available training history."
                    ),
                }
            )

    inferred_mono = dict(profile.monotonic_constraints) or infer_monotonic_constraints(
        [*profile.future_covariates, *profile.past_covariates]
    )
    if inferred_mono:
        rationales.append(
            {
                "category": "features",
                "parameter": "features.monotonic_constraints",
                "value": str(inferred_mono),
                "evidence": f"price/promo drivers detected: {list(inferred_mono.keys())}",
                "rationale": (
                    "Enforces structural sign guardrails (negative price elasticity, "
                    "non-negative promotional lift) on tree and linear lag learners."
                ),
            }
        )

    return {
        "models": models,
        "model_params": model_params,
        "scale_regime": scale_regime,
        "trim_leading_zeros": trim_leading_zeros,
        "grid_policy": grid_policy,
        "target_transform": target_transform,
        "simplex_sum": simplex_sum,
        "outlier_policy": outlier_policy,
        "level_shift": level_shift,
        "trading_days": trading_days,
        "fourier": fourier,
        "censored_col": censored_col,
        "monotonic_constraints": inferred_mono,
        "horizon_strategy": "recursive",
        "regime_routing": regime_routing,
        "include_univariate_baselines": include_univariate_baselines,
        "ablation_modes": ablation_modes,
        "ensemble_strategies": ensemble_strategies,
        "ensemble_top_k": ensemble_top_k,
        "parsimony_margin": parsimony_margin,
        "selection_rule": selection_rule,
        "n_folds": n_folds,
        "hpo_enabled": hpo_enabled,
        "hpo_trials": hpo_trials,
        "hpo_granularity": hpo_granularity,
        "floor": floor,
        "integer_rounding": integer_rounding,
        "underage_cost": underage_cost,
        "overage_cost": overage_cost,
        "target_quantile": target_quantile,
        "quantiles": quantiles,
        "decision_metric": decision_metric,
        "rationales": rationales,
    }