Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(settings): skip the client reset when an apply changes nothing (#1421) (#1436)

ZQR11014f48ea794369
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 69ef55688..1dc54afec 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -361,14 +361,27 @@ class DocumentParsingInstall(BaseModel):
engine: str
-def _invalidate_runtime_caches() -> None:
+def _invalidate_runtime_caches(
+ *,
+ catalog_before: dict[str, Any] | None = None,
+ catalog_after: dict[str, Any] | None = None,
+) -> None:
"""Force runtime clients/config to pick up the latest saved catalog.
The LLM and embedding clients are process-wide singletons, so resetting
them here will affect any user turn that is mid-flight on another worker.
Admins issuing Apply during active sessions accept that trade-off; we log
a WARNING so the cause is visible in the audit trail.
+
+ An apply whose saved catalog equals the one the clients were built from
+ changes nothing they would read, so it skips the reset: the runtime
+ resolves from this one file, so an equal catalog means an equal client.
+ That is the shape a settings visit re-applying the same configuration
+ takes, and each redundant reset used to flip the client out from under an
+ in-flight turn and hang it in the provider retry ladder (#1421).
"""
+ if catalog_before is not None and catalog_after is not None and catalog_before == catalog_after:
+ return
logger.warning(
"Admin applied catalog; resetting global LLM/embedding clients. "
"In-flight user turns may flip backend client mid-call."
@@ -876,6 +889,7 @@ async def update_openai_codex_reasoning_effort(
payload: CodexReasoningEffortUpdate,
) -> dict[str, Any]:
_require_codex_oauth_actor()
+ catalog_before = get_model_catalog_service().load()
try:
status_payload = await get_codex_oauth_service().set_reasoning_effort(
payload.model,
@@ -886,7 +900,10 @@ async def update_openai_codex_reasoning_effort(
# This writes the catalog the runtime resolves against, like every other
# catalog write here — without it the next turn keeps the old effort until
# something else happens to invalidate.
- _invalidate_runtime_caches()
+ _invalidate_runtime_caches(
+ catalog_before=catalog_before,
+ catalog_after=get_model_catalog_service().load(),
+ )
return status_payload
@@ -1457,7 +1474,7 @@ async def update_catalog(payload: CatalogPayload):
restored = restore_catalog_secrets(payload.catalog, current)
proposed = reconcile_codex_catalog_update(current, restored)
catalog = service.save(proposed)
- _invalidate_runtime_caches()
+ _invalidate_runtime_caches(catalog_before=current, catalog_after=catalog)
return {"catalog": redact_catalog_secrets(catalog)}
@@ -1498,7 +1515,7 @@ async def apply_catalog_service(payload: CatalogServicePayload):
else:
public_draft = redact_draft(draft_service.save(stored_draft))
- _invalidate_runtime_caches()
+ _invalidate_runtime_caches(catalog_before=current, catalog_after=catalog)
return {
"message": f"{payload.service} settings applied to runtime.",
"catalog": redact_catalog_secrets(catalog),
@@ -1570,11 +1587,12 @@ async def apply_catalog(payload: CatalogPayload | None = None):
)
catalog = reconcile_codex_catalog_update(current, proposed)
applied = service.apply(catalog)
+ catalog_after = service.load()
draft_service.clear()
- _invalidate_runtime_caches()
+ _invalidate_runtime_caches(catalog_before=current, catalog_after=catalog_after)
return {
"message": "Catalog applied to runtime settings.",
- "catalog": redact_catalog_secrets(service.load()),
+ "catalog": redact_catalog_secrets(catalog_after),
"runtime": applied,
}
@@ -1843,7 +1861,7 @@ async def complete_tour(payload: TourCompletePayload | None = None):
else current
)
applied = service.apply(catalog)
- _invalidate_runtime_caches()
+ _invalidate_runtime_caches(catalog_before=current, catalog_after=service.load())
now = int(time.time())
launch_at = now + 3
redirect_at = now + 5
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index a52964a14..1ca3c8a3b 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -777,6 +777,70 @@ async def test_apply_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monk
assert new_embedding_client.config.model == "text-embedding-after-apply"
+async def test_reapplying_an_unchanged_catalog_keeps_the_runtime_clients(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An apply that changes nothing must not reset the shared clients.
+
+ The clients are process-wide singletons; resetting them flips the client
+ out from under any turn that is mid-call and hangs that turn in the
+ provider retry ladder. A settings visit that re-applies the same
+ configuration — the shape a cold-start first message keeps meeting
+ (#1421) — has nothing to invalidate.
+ """
+ catalog = _build_catalog(
+ llm_model="gpt-same",
+ llm_base_url="https://same-llm.example/v1",
+ llm_api_key="same-llm-key",
+ embedding_model="text-embedding-same",
+ embedding_base_url="https://same-embedding.example/v1/embeddings",
+ embedding_api_key="same-embedding-key",
+ )
+ service = _FakeCatalogService(catalog)
+ _patch_runtime(monkeypatch, service)
+
+ llm_config_module.get_llm_config()
+ old_llm_client = llm_client_module.get_llm_client()
+ old_embedding_client = embedding_client_module.get_embedding_client()
+
+ response = await settings_router.apply_catalog(settings_router.CatalogPayload(catalog=catalog))
+
+ new_llm_client = llm_client_module.get_llm_client()
+ new_embedding_client = embedding_client_module.get_embedding_client()
+
+ assert response["catalog"] == settings_router.redact_catalog_secrets(catalog)
+ assert new_llm_client is old_llm_client
+ assert new_embedding_client is old_embedding_client
+ assert new_llm_client.config.model == "gpt-same"
+
+
+async def test_re_saving_an_unchanged_catalog_keeps_the_runtime_clients(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``PUT /catalog`` with the stored catalog skips the reset too."""
+ catalog = _build_catalog(
+ llm_model="gpt-put",
+ llm_base_url="https://put-llm.example/v1",
+ llm_api_key="put-llm-key",
+ embedding_model="text-embedding-put",
+ embedding_base_url="https://put-embedding.example/v1/embeddings",
+ embedding_api_key="put-embedding-key",
+ )
+ service = _FakeCatalogService(catalog)
+ _patch_runtime(monkeypatch, service)
+
+ old_llm_client = llm_client_module.get_llm_client()
+ old_embedding_client = embedding_client_module.get_embedding_client()
+
+ response = await settings_router.update_catalog(settings_router.CatalogPayload(catalog=catalog))
+
+ assert response == {"catalog": settings_router.redact_catalog_secrets(catalog)}
+ assert llm_client_module.get_llm_client() is old_llm_client
+ assert embedding_client_module.get_embedding_client() is old_embedding_client
+
+
@pytest.mark.asyncio
async def test_apply_catalog_service_only_promotes_the_selected_service_and_updates_saved_draft(
monkeypatch: pytest.MonkeyPatch, tmp_path
@@ -817,7 +881,7 @@ async def test_apply_catalog_service_only_promotes_the_selected_service_and_upda
draft_service.save({"catalog": draft, "extensions": {"network": {"backend_port": 9000}}})
monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: catalog_service)
monkeypatch.setattr(settings_router, "get_settings_draft_service", lambda: draft_service)
- monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)
+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda **kwargs: None)
response = await settings_router.apply_catalog_service(
settings_router.CatalogServicePayload(service="stt", config=draft["services"]["stt"])
@@ -852,7 +916,7 @@ async def test_update_catalog_restores_masked_secrets(monkeypatch: pytest.Monkey
)
service = _FakeCatalogService(current)
monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)
- monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)
+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda **kwargs: None)
draft = settings_router.redact_catalog_secrets(current)
draft["services"]["llm"]["profiles"][0]["name"] = "Renamed"
@@ -901,7 +965,7 @@ async def test_catalog_writes_preserve_current_managed_codex_metadata(
current["services"]["llm"]["active_model_id"] = managed_model["id"]
service = _FakeCatalogService(current)
monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)
- monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)
+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda **kwargs: None)
stale_draft = deepcopy(current)
stale_draft["services"]["embedding"]["profiles"][0]["name"] = "Unsaved edit"
@@ -958,7 +1022,7 @@ async def test_catalog_write_rejects_unbound_or_cross_account_codex_reasoning_ch
current["services"]["llm"]["profiles"].append(current_profile)
service = _FakeCatalogService(current)
monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)
- monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)
+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda **kwargs: None)
stale_draft = deepcopy(current)
stale_profile = stale_draft["services"]["llm"]["profiles"][1]
@@ -1002,7 +1066,7 @@ async def test_catalog_write_uses_current_managed_codex_profile_presence(
stale_draft["services"]["llm"]["profiles"].append(managed_profile)
service = _FakeCatalogService(current)
monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)
- monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)
+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda **kwargs: None)
await settings_router.update_catalog(settings_router.CatalogPayload(catalog=stale_draft))
@@ -1036,7 +1100,7 @@ async def test_incomplete_catalog_write_preserves_the_current_managed_codex_prof
current["services"]["llm"]["profiles"].append(managed_profile)
service = _FakeCatalogService(current)
monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)
- monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)
+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda **kwargs: None)
payload = settings_router.CatalogPayload(catalog={"version": 1})
if operation == "save":