Skip to content

Self-improving AI Employees for everyone

fix(llm): fail a save the credential store did not accept

trohitg3e3bee16d6b9
diff --git a/server/nodes/model/_local_validator.py b/server/nodes/model/_local_validator.py
index 426f428c..fb176199 100644
--- a/server/nodes/model/_local_validator.py
+++ b/server/nodes/model/_local_validator.py
@@ -95,6 +95,20 @@ def _failure(provider_ref: str, message: str) -> Dict[str, Any]:
}
+def _store_failed(display: str) -> str:
+ return f"Could not save {display}: the credential store did not accept the write. See the server log."
+
+
+async def _restore_url_row(auth_service: Any, url_key: str, previous: Optional[str]) -> None:
+ """Undo the URL-row write of a save whose key-row write failed (D5)."""
+ if previous:
+ restored = await auth_service.store_api_key(provider=url_key, api_key=previous, models=[])
+ else:
+ restored = await auth_service.remove_api_key(url_key)
+ if not restored:
+ logger.error("LLM server save could not restore its URL row", provider=url_key)
+
+
def _strip_v1_path(base_url: str) -> str:
"""Return ``base_url`` with a trailing ``/v1`` segment stripped.
@@ -368,15 +382,21 @@ async def save_llm_server(
}
auth_service = get_auth_service()
+ url_key = base_url_key(provider_ref)
+ previous_url = await auth_service.get_api_key(url_key)
# The URL row first: a key row with no URL row is exactly what the
- # runtime reports as "not configured".
- await auth_service.store_api_key(provider=base_url_key(provider_ref), api_key=base_url, models=[])
- await auth_service.store_api_key(
+ # runtime reports as "not configured". store_api_key reports a failed
+ # write by returning False; a save it rejected is not a save.
+ if not await auth_service.store_api_key(provider=url_key, api_key=base_url, models=[]):
+ return _failure(provider_ref, _store_failed(display))
+ if not await auth_service.store_api_key(
provider=provider_ref,
api_key=api_key,
models=models,
model_params={**model_params, SERVER_META_KEY: server_meta},
- )
+ ):
+ await _restore_url_row(auth_service, url_key, previous_url)
+ return _failure(provider_ref, _store_failed(display))
# Keep the sync ``get_context_length`` / ``get_max_output_tokens``
# lookups on the real per-model values without a DB read per call.
diff --git a/server/tests/nodes/test_local_llm_save.py b/server/tests/nodes/test_local_llm_save.py
index 0e56ab9a..ae0ca5df 100644
--- a/server/tests/nodes/test_local_llm_save.py
+++ b/server/tests/nodes/test_local_llm_save.py
@@ -30,8 +30,13 @@ class FakeAuth:
def __init__(self) -> None:
self.rows: Dict[str, Dict[str, Any]] = {}
self.stored: List[str] = []
+ # Providers whose write the store rejects, as AuthService does on a
+ # database error: it logs and returns False.
+ self.rejects: set = set()
async def store_api_key(self, provider, api_key, models, session_id="default", model_params=None):
+ if provider in self.rejects:
+ return False
self.stored.append(provider)
self.rows[provider] = {"key": api_key, "models": list(models), "model_params": model_params or {}}
return True
@@ -40,6 +45,10 @@ class FakeAuth:
row = self.rows.get(provider)
return row["key"] if row else None
+ async def remove_api_key(self, provider, session_id="default") -> bool:
+ self.rows.pop(provider, None)
+ return True
+
@pytest.fixture
def auth(monkeypatch) -> FakeAuth:
@@ -137,6 +146,39 @@ class TestFailedSaveChangesNothing:
assert auth.stored == []
broadcaster.update_api_key_status.assert_not_awaited()
+ @staticmethod
+ def _llamacpp_at(base: str) -> None:
+ respx.get(f"{base}/models").mock(return_value=httpx.Response(200, json=_models("model.gguf")))
+ respx.get(f"{base}/props").mock(
+ return_value=httpx.Response(200, json={"default_generation_settings": {"n_ctx": 8192}})
+ )
+
+ @respx.mock
+ async def test_a_rejected_key_row_puts_the_old_url_back(self, auth, broadcaster, registry):
+ auth.rows[f"{REF}_proxy"] = {"key": "http://old:8080", "models": [], "model_params": {}}
+ auth.rejects.add(REF)
+ self._llamacpp_at("http://host:8080")
+
+ result = await lv.save_llm_server(REF, "http://host:8080", None, display="llama", label="llama")
+
+ assert result["valid"] is False
+ assert "did not accept the write" in result["message"]
+ assert auth.rows[f"{REF}_proxy"]["key"] == "http://old:8080"
+ assert REF not in auth.rows
+ assert registry.get_model_info("model.gguf", REF) is None
+ broadcaster.update_api_key_status.assert_not_awaited()
+
+ @respx.mock
+ async def test_a_rejected_first_save_leaves_no_url_row(self, auth, broadcaster, registry):
+ auth.rejects.add(REF)
+ self._llamacpp_at("http://host:8080")
+
+ result = await lv.save_llm_server(REF, "http://host:8080", None, display="llama", label="llama")
+
+ assert result["valid"] is False
+ assert auth.rows == {}
+ broadcaster.update_api_key_status.assert_not_awaited()
+
class TestSaveByKind:
@respx.mock