From 2fee28289b2d391043207c88bcda4ac7b5680a6e Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:00:19 -0800 Subject: [PATCH] fix: pair the resumed model with its saved route after /model then fallback A /model switch before the first reply saved the nested gateway_runtime route, then a fallback serving that first call rewrote only the model column, and resume read the fallback model with the switched provider. Every route writer now stamps its model into gateway_runtime, and session_resume_route returns the model and route together from one record (no replacement row for callers). --- gateway/run_turn_prepare.py | 1 + hermes_cli/cli_model_switch_mixin.py | 5 ++-- hermes_state_gateway.py | 26 +++++++++++-------- hermes_state_sessions.py | 4 ++- .../test_resume_switched_provider_endpoint.py | 16 ++++++++++++ tui_gateway/agent_factory.py | 3 +-- 6 files changed, 38 insertions(+), 17 deletions(-) diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py index b124513ced..f19212ca78 100644 --- a/gateway/run_turn_prepare.py +++ b/gateway/run_turn_prepare.py @@ -366,6 +366,7 @@ class GatewayTurnPrepareMixin: getattr(agent, "base_url", None), model), "base_url": getattr(agent, "base_url", None), "api_mode": getattr(agent, "api_mode", None), + "model": model, } runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False)) runtime = {k: v for k, v in runtime.items() if v not in (None, "")} diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py index 26a9cc8e0c..0a707d28a8 100644 --- a/hermes_cli/cli_model_switch_mixin.py +++ b/hermes_cli/cli_model_switch_mixin.py @@ -56,10 +56,9 @@ def stored_session_route(session_meta, *, current_model, current_provider): else the TUI's top-level keys). Bare ``custom`` is healed because the CLI resolve path hard-fails on it (the TUI gateway keeps it when a base_url exists).""" from hermes_state import SessionDB as _SessionDB - stored_model, route_row = _SessionDB.session_resume_model(session_meta) + stored_model, runtime = _SessionDB.session_resume_route(session_meta) if not stored_model: return None - runtime = _SessionDB.session_gateway_runtime(route_row) base_url = runtime.get("base_url") or None api_mode = runtime.get("api_mode") or None stored_provider = runtime.get("provider") or None @@ -560,7 +559,7 @@ class CLIModelSwitchMixin: "api_mode": result.api_mode or None} try: db.update_session_model(sid, result.new_model) - db.patch_session_model_config(sid, {"gateway_runtime": route, **route}) + db.patch_session_model_config(sid, {"gateway_runtime": {**route, "model": result.new_model or None}, **route}) except Exception: logger.debug("Failed to persist model switch to session DB", exc_info=True) diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py index 864b24a48c..3de8d13ab8 100644 --- a/hermes_state_gateway.py +++ b/hermes_state_gateway.py @@ -929,16 +929,16 @@ class SessionGatewayMixin: return counts @staticmethod - def session_resume_model(session_meta: Optional[dict[str, Any]]) -> tuple[str, dict[str, Any]]: - """``(model, route_row)`` a resumed session runs: the model plus the row to read its route from - (``session_gateway_runtime``), so the pair always comes from one record. + def session_resume_route(session_meta: Optional[dict[str, Any]]) -> tuple[str, dict[str, Any]]: + """``(model, route)`` a resumed session runs, both from one record so they always pair. The ``model`` column is the billing record: the first accounted call rewrites it to whatever - served it, a turn-scoped fallback included, and leaves ``model_config`` alone. So the pick in - ``model_config.model`` wins, except where the column was written together with its route: a - ``gateway_runtime`` with a provider (gateway route sync, CLI/gateway ``/model``), or a confirmed - Browser/API lock still naming the column. ``billing_provider`` served the column model, so it - never fills the provider of a different pick.""" + served it, a turn-scoped fallback included, and touches nothing in ``model_config``. So the + model comes from the record the route comes from: a ``gateway_runtime`` route's own ``model`` + (every route writer stamps it), else the pick in ``model_config.model``. The column is used + only where nothing else names a model, plus two legacy cases written with the column: a + ``gateway_runtime`` from before the stamp, and a confirmed Browser/API lock still naming it. + ``billing_provider`` served the column model, so it never fills the provider of another.""" row = session_meta or {} raw = row.get("model_config") if isinstance(raw, str): @@ -950,12 +950,16 @@ class SessionGatewayMixin: column = str(row.get("model") or "").strip() picked = str(config.get("model") or "").strip() runtime, lock = config.get("gateway_runtime"), config.get("browser_model_lock") - locked = isinstance(lock, dict) and bool(lock.get("confirmed")) and str(lock.get("model") or "").strip() == column - if (isinstance(runtime, dict) and runtime.get("provider")) or locked: + if isinstance(runtime, dict) and runtime.get("provider"): + model = str(runtime.get("model") or "").strip() or column or picked + elif isinstance(lock, dict) and lock.get("confirmed") and str(lock.get("model") or "").strip() == column: model = column or picked else: model = picked or column - return model, (row if model == column else {**row, "billing_provider": None}) + route_row = row if model == column else {**row, "billing_provider": None} + route = SessionGatewayMixin.session_gateway_runtime(route_row) + route.pop("model", None) + return model, route @staticmethod def session_gateway_runtime(session_meta: Optional[dict[str, Any]]) -> dict[str, Any]: diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py index 476b3ef51d..a069029262 100644 --- a/hermes_state_sessions.py +++ b/hermes_state_sessions.py @@ -740,7 +740,9 @@ class SessionSessionsMixin: patch["model"] = model if provider: route = {"provider": provider, "base_url": base_url or None, "api_mode": api_mode or None} - patch.update(route, gateway_runtime=route) + # The nested route names its model: the first accounted call may later rewrite the model + # column to a fallback, and resume must still pair this provider with this model. + patch.update(route, gateway_runtime={**route, "model": model or None}) self._write_model_config_patch( session_id, patch, "UPDATE sessions SET model = ?, model_config = ? WHERE id = ?", lambda merged: (model, merged, session_id), diff --git a/tests/tui_gateway/test_resume_switched_provider_endpoint.py b/tests/tui_gateway/test_resume_switched_provider_endpoint.py index 13d1258531..34169a99f4 100644 --- a/tests/tui_gateway/test_resume_switched_provider_endpoint.py +++ b/tests/tui_gateway/test_resume_switched_provider_endpoint.py @@ -75,6 +75,22 @@ def test_resume_after_fallback_served_first_call_keeps_the_picked_pair(tmp_path) "claude-opus-4", "anthropic") +def test_resume_after_model_switch_then_fallback_first_call_keeps_the_switched_pair(tmp_path): + """``/model`` before the first reply writes the nested route; a fallback serving that first call then + rewrites only the model column. Resume must keep the switched pair, not the fallback model on it.""" + db = SessionDB(db_path=tmp_path / "state.db") + db.create_session("s1", source="cli", model="gpt-6-sol") + db.update_session_model("s1", "claude-opus-4", provider="anthropic") + db.update_token_counts("s1", input_tokens=10, output_tokens=5, model="deepseek/deepseek-v4-flash", + billing_provider="openrouter", api_call_count=1) + row = db.get_session("s1") + assert row["model"] == "deepseek/deepseek-v4-flash" + restored = _stored_session_runtime_overrides(row)["model_override"] + assert (restored["model"], restored["provider"]) == ("claude-opus-4", "anthropic") + assert stored_session_route(row, current_model="gpt-6-sol", current_provider="nous")[:2] == ( + "claude-opus-4", "anthropic") + + @pytest.mark.parametrize("picked", [ {"model": "claude-opus-4", "provider": "anthropic"}, {"model": "claude-opus-4"}, diff --git a/tui_gateway/agent_factory.py b/tui_gateway/agent_factory.py index 11fe0b2498..7e958440a9 100644 --- a/tui_gateway/agent_factory.py +++ b/tui_gateway/agent_factory.py @@ -142,8 +142,7 @@ def _stored_session_runtime_overrides(row: dict | None) -> dict: # billing column; then nested ``gateway_runtime`` before the TUI's top-level keys, then a routable # ``billing_provider`` (#125942). from hermes_state import SessionDB - model, route_row = SessionDB.session_resume_model(row) - route = SessionDB.session_gateway_runtime(route_row) + model, route = SessionDB.session_resume_route(row) provider, base_url, api_mode = (str(route.get(k) or "").strip() for k in ("provider", "base_url", "api_mode")) service_tier = str(model_config.get("service_tier") or "").strip() reasoning_config = model_config.get("reasoning_config")