DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(settings): one place decides whether a catalog write reset the clients
Bingxi Zhao (Frank)6f618f1abfe5
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 1dc54afec..5e03fe18b 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -8,6 +8,8 @@ UI preferences, configuration catalog management, and detailed streamed tests.from __future__ import annotationsimport asyncio+from collections.abc import Iterator+import contextlibfrom copy import deepcopyimport jsonimport logging@@ -361,26 +363,34 @@ class DocumentParsingInstall(BaseModel):engine: str-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).+def _runtime_catalog_write() -> Iterator[None]:+ """Bracket a write to the model catalog, resetting clients if it landed.++ The LLM and embedding clients are process-wide singletons that resolve+ from this one file, so resetting them affects any user turn mid-flight on+ another worker; admins issuing Apply during active sessions accept that,+ and the WARNING keeps the cause in the audit trail.++ An apply that saved the catalog already on disk changes nothing those+ clients would read. That is the shape a settings visit re-applying the+ same configuration takes, and each redundant reset flipped the backend+ client out from under an in-flight turn and dropped it into the provider+ retry ladder — the cold start whose first message sat in a loop until a+ restart (#1421).++ Whether the catalog changed is a property of the file, not of the caller,+ so both sides are read here. Five endpoints each assembling their own+ before/after pair is five chances to pair the wrong two and a sixth+ endpoint's chance to forget; wrapping the write is the whole contract.++ A write that raises leaves the block without resetting, which is what a+ failed write should do: there is nothing new for the clients to read."""- if catalog_before is not None and catalog_after is not None and catalog_before == catalog_after:+ service = get_model_catalog_service()+ before = service.load()+ yield+ if service.load() == before:returnlogger.warning("Admin applied catalog; resetting global LLM/embedding clients. "@@ -889,21 +899,17 @@ 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,- payload.reasoning_effort,- )- except CodexAuthError as exc:- raise _codex_http_exception(exc) from None- # 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(- catalog_before=catalog_before,- catalog_after=get_model_catalog_service().load(),- )+ # The codex service writes the catalog the runtime resolves against, like+ # every other catalog write here — unbracketed, the next turn would keep+ # the old effort until something else happened to reset the clients.+ with _runtime_catalog_write():+ try:+ status_payload = await get_codex_oauth_service().set_reasoning_effort(+ payload.model,+ payload.reasoning_effort,+ )+ except CodexAuthError as exc:+ raise _codex_http_exception(exc) from Nonereturn status_payload@@ -1473,8 +1479,8 @@ async def update_catalog(payload: CatalogPayload):current = service.load()restored = restore_catalog_secrets(payload.catalog, current)proposed = reconcile_codex_catalog_update(current, restored)- catalog = service.save(proposed)- _invalidate_runtime_caches(catalog_before=current, catalog_after=catalog)+ with _runtime_catalog_write():+ catalog = service.save(proposed)return {"catalog": redact_catalog_secrets(catalog)}@@ -1494,7 +1500,8 @@ async def apply_catalog_service(payload: CatalogServicePayload):proposed.setdefault("services", {})[payload.service] = deepcopy(payload.config)restored = restore_catalog_secrets(proposed, current)reconciled = reconcile_codex_catalog_update(current, restored)- runtime = service.apply(reconciled)+ with _runtime_catalog_write():+ runtime = service.apply(reconciled)catalog = service.load()# A previously saved draft contains a full catalog. Keep it, but advance@@ -1515,7 +1522,6 @@ async def apply_catalog_service(payload: CatalogServicePayload):else:public_draft = redact_draft(draft_service.save(stored_draft))- _invalidate_runtime_caches(catalog_before=current, catalog_after=catalog)return {"message": f"{payload.service} settings applied to runtime.","catalog": redact_catalog_secrets(catalog),@@ -1586,10 +1592,10 @@ async def apply_catalog(payload: CatalogPayload | None = None):else current)catalog = reconcile_codex_catalog_update(current, proposed)- applied = service.apply(catalog)+ with _runtime_catalog_write():+ applied = service.apply(catalog)catalog_after = service.load()draft_service.clear()- _invalidate_runtime_caches(catalog_before=current, catalog_after=catalog_after)return {"message": "Catalog applied to runtime settings.","catalog": redact_catalog_secrets(catalog_after),@@ -1860,8 +1866,8 @@ async def complete_tour(payload: TourCompletePayload | None = None):if payload and payload.catalogelse current)- applied = service.apply(catalog)- _invalidate_runtime_caches(catalog_before=current, catalog_after=service.load())+ with _runtime_catalog_write():+ applied = service.apply(catalog)now = int(time.time())launch_at = now + 3redirect_at = now + 5diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex 1ca3c8a3b..cc4f09b33 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -1,5 +1,6 @@from __future__ import annotations+import contextlibfrom copy import deepcopyimport jsonfrom types import SimpleNamespace@@ -841,6 +842,67 @@ async def test_re_saving_an_unchanged_catalog_keeps_the_runtime_clients(assert embedding_client_module.get_embedding_client() is old_embedding_client+async def test_finishing_the_tour_without_edits_keeps_the_runtime_clients(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """The tour is the cold start #1421 described, and it applies on exit.++ Completing it with nothing changed used to reset the shared clients while+ the learner's first message was already in flight.+ """+ catalog = _build_catalog(+ llm_model="gpt-tour",+ llm_base_url="https://tour-llm.example/v1",+ llm_api_key="tour-llm-key",+ embedding_model="text-embedding-tour",+ embedding_base_url="https://tour-embedding.example/v1/embeddings",+ embedding_api_key="tour-embedding-key",+ )+ service = _FakeCatalogService(catalog)+ _patch_runtime(monkeypatch, service)+ monkeypatch.setattr(settings_router, "_tour_cache_file", lambda: tmp_path / "tour.json")++ old_llm_client = llm_client_module.get_llm_client()+ old_embedding_client = embedding_client_module.get_embedding_client()++ await settings_router.complete_tour(None)++ assert llm_client_module.get_llm_client() is old_llm_client+ assert embedding_client_module.get_embedding_client() is old_embedding_client+++async def test_reapplying_one_unchanged_service_keeps_the_runtime_clients(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Applying a single service that already holds that value resets nothing."""+ catalog = _build_catalog(+ llm_model="gpt-service",+ llm_base_url="https://service-llm.example/v1",+ llm_api_key="service-llm-key",+ embedding_model="text-embedding-service",+ embedding_base_url="https://service-embedding.example/v1/embeddings",+ embedding_api_key="service-embedding-key",+ )+ from deeptutor.services.config.settings_draft import SettingsDraftService++ service = _FakeCatalogService(catalog)+ _patch_runtime(monkeypatch, service)+ draft_service = SettingsDraftService(tmp_path / "settings_draft.json")+ monkeypatch.setattr(settings_router, "get_settings_draft_service", lambda: draft_service)++ old_llm_client = llm_client_module.get_llm_client()+ old_embedding_client = embedding_client_module.get_embedding_client()++ await settings_router.apply_catalog_service(+ settings_router.CatalogServicePayload(service="llm", config=catalog["services"]["llm"])+ )++ assert llm_client_module.get_llm_client() is old_llm_client+ assert embedding_client_module.get_embedding_client() is old_embedding_client++@pytest.mark.asyncioasync def test_apply_catalog_service_only_promotes_the_selected_service_and_updates_saved_draft(monkeypatch: pytest.MonkeyPatch, tmp_path@@ -881,7 +943,7 @@ async def test_apply_catalog_service_only_promotes_the_selected_service_and_updadraft_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 **kwargs: None)+ monkeypatch.setattr(settings_router, "_runtime_catalog_write", contextlib.nullcontext)response = await settings_router.apply_catalog_service(settings_router.CatalogServicePayload(service="stt", config=draft["services"]["stt"])@@ -916,7 +978,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 **kwargs: None)+ monkeypatch.setattr(settings_router, "_runtime_catalog_write", contextlib.nullcontext)draft = settings_router.redact_catalog_secrets(current)draft["services"]["llm"]["profiles"][0]["name"] = "Renamed"@@ -965,7 +1027,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 **kwargs: None)+ monkeypatch.setattr(settings_router, "_runtime_catalog_write", contextlib.nullcontext)stale_draft = deepcopy(current)stale_draft["services"]["embedding"]["profiles"][0]["name"] = "Unsaved edit"@@ -1022,7 +1084,7 @@ async def test_catalog_write_rejects_unbound_or_cross_account_codex_reasoning_chcurrent["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 **kwargs: None)+ monkeypatch.setattr(settings_router, "_runtime_catalog_write", contextlib.nullcontext)stale_draft = deepcopy(current)stale_profile = stale_draft["services"]["llm"]["profiles"][1]@@ -1066,7 +1128,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 **kwargs: None)+ monkeypatch.setattr(settings_router, "_runtime_catalog_write", contextlib.nullcontext)await settings_router.update_catalog(settings_router.CatalogPayload(catalog=stale_draft))@@ -1100,7 +1162,7 @@ async def test_incomplete_catalog_write_preserves_the_current_managed_codex_profcurrent["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 **kwargs: None)+ monkeypatch.setattr(settings_router, "_runtime_catalog_write", contextlib.nullcontext)payload = settings_router.CatalogPayload(catalog={"version": 1})if operation == "save":