Ostatni krok fazy 4 KB (plan §2 Decyzja 2, §5): kb-query przestaje być martwe
przez ~16 h/dobę, gdy SOLARIA (GPU) śpi — zapytania embeduje wtedy lokalna
Ollama CPU na PIHA (wolniej: ~790 ms+ vs ~207 ms na GPU, ale działa).
Nowy serwis services/ollama-piha (GitOps, owner_node: piha):
- ollama/ollama:latest (arm64 natywnie), OLLAMA_KEEP_ALIVE=0 — model zwalnia
RAM natychmiast po każdym wywołaniu (spike, nie rezydent; PIHA dzieli 8 GB z HA)
- bind wyłącznie 127.0.0.1 + LAN_BIND_IP (192.168.31.5), nigdy 0.0.0.0/Tailscale
- named volume ollama_piha_models (NVMe data-root) zamiast bind-mounta — obraz
biega jako root w kontenerze i bind łamałby wzorzec uid PIHA (oskar=1004,
kontenery uid 1000, setgid pi)
- override hosts/piha/runtime/ollama-piha: mem_limit 2560m (wartość startowa
z planu, do potwierdzenia kalibracją na żywo), świadomie bez mem_reservation
- pull bge-m3 to jawny, ręczny krok deployu (README) — obraz nie ma modeli
kb-query — maszyna stanów fallbacku (app/embed_router.py):
- health-check SOLARII (GET /api/tags, timeout 1.5 s) z cache 30 s — zero
sondowania per request; po powrocie SOLARII ruch wraca na GPU w ≤30 s
- primary up → embed na SOLARII z twardym timeoutem 3 s; błąd W TRAKCIE
zapytania = jednorazowe przełączenie (krok 3b planu): status down na 30 s
i TO SAMO zapytanie leci na fallback — user nie widzi błędu SOLARII
- primary down → embed prosto na ollama-piha (bez twardego timeoutu: CPU +
zimny load modelu to legalnie pojedyncze sekundy)
- 503 tylko gdy oba backendy padłe (lub fallback nieskonfigurowany)
- inwariant modelu, druga połowa: każdy backend weryfikowany raz, leniwie przy
pierwszym użyciu, że /api/tags zawiera EMBED_MODEL (bge-m3 — ta sama wartość
co startowy check przeciw document_chunk.model/document_summary.embedding_model);
niezgodność = ERROR log + 500, nigdy ciche liczenie dystansów między
różnymi przestrzeniami embeddingów; leniwie, bo śpiąca SOLARIA nie może
blokować startu serwisu
- odpowiedź /search: nowe pole embed_backend ("solaria"|"piha") + sol_status
wg realnego świata routera (UI już renderuje down jako "offline (fallback
embed)"); log INFO backend=... elapsed_ms=... per zapytanie
- /healthz: sol_status przez cache routera (spójny widok z routingiem) +
fallback_status (żywa, tania sonda /api/tags)
Konfiguracja spójnie przez env (compose + env.example + service.yaml + README):
EMBED_PRIMARY_URL (zastępuje OLLAMA_URL), EMBED_FALLBACK_URL (pusty = brak
fallbacku, zachowanie sprzed kroku 2), EMBED_{PRIMARY,FALLBACK}_NAME,
EMBED_HEALTH_TTL_S/EMBED_HEALTH_TIMEOUT_S/EMBED_PRIMARY_TIMEOUT_S.
Testy: 39 pass (14 nowych w test_embed_router.py: cache TTL, failover w trakcie
zapytania, powrót po TTL, oba padłe, mismatch modelu na primary i fallbacku,
tag "bge-m3:latest" vs "bge-m3"); docker build + smoke (importy + uvicorn do
guardu KB_DSN) OK; compose config OK dla obu stacków.
Deploy (Oskar, na PIHA z mastera po merge):
cd ~/homelab-codex-ws && git pull
# 1. ollama-piha
cp services/ollama-piha/env.example services/ollama-piha/.env
docker compose -f services/ollama-piha/docker-compose.yml \
-f hosts/piha/runtime/ollama-piha/docker-compose.override.yml \
--env-file services/ollama-piha/.env up -d
docker exec ollama-piha ollama pull bge-m3 # ręczny krok, obowiązkowy
services/ollama-piha/healthcheck.sh
# 2. kb-query (dopisać fallback do istniejącego .env)
echo 'EMBED_FALLBACK_URL=http://192.168.31.5:11434' >> services/kb-query/.env
docker compose -f services/kb-query/docker-compose.yml \
-f hosts/piha/runtime/kb-query/docker-compose.override.yml up -d --build
services/kb-query/healthcheck.sh
# (deploy-node.sh też podniesie oba serwisy z hosts/piha/services.yaml,
# ale pull bge-m3 i .env pozostają ręczne)
Weryfikacja: testy A/B/C w services/kb-query/README.md (backend=solaria przy
SOLARII online; backend=piha przy symulacji offline; powrót na GPU w ≤30 s).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
225 lines
8.6 KiB
Python
225 lines
8.6 KiB
Python
"""Unit tests for the SOLARIA->PIHA embed fallback state machine (app.embed_router) -- no
|
|
real Ollama on either side. Fake backends are keyed by URL so one fake session can serve
|
|
both legs; the clock is injected so the 30 s TTL is tested without sleeping."""
|
|
from __future__ import annotations
|
|
|
|
import pathlib
|
|
import sys
|
|
|
|
import aiohttp
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from app.embed_router import EmbedBackendError, EmbedRouter, ModelMismatchError # noqa: E402
|
|
|
|
PRIMARY = "http://solaria:11434"
|
|
FALLBACK = "http://192.168.31.5:11434"
|
|
|
|
|
|
class _FakeResponse:
|
|
def __init__(self, payload=None, exc=None, status=200):
|
|
self._payload = payload
|
|
self._exc = exc
|
|
self.status = status # check_ollama_health reads resp.status directly
|
|
|
|
async def __aenter__(self):
|
|
if self._exc is not None:
|
|
raise self._exc
|
|
return self
|
|
|
|
async def __aexit__(self, *exc):
|
|
return False
|
|
|
|
def raise_for_status(self):
|
|
pass
|
|
|
|
async def json(self):
|
|
return self._payload
|
|
|
|
|
|
class _FakeBackend:
|
|
"""One fake Ollama: `models` drives /api/tags, `down=True` refuses every connection,
|
|
`embed_exc` makes /api/embeddings fail while /api/tags still answers (the plan's step-3b
|
|
scenario: probe says up, the real embed then dies mid-query)."""
|
|
|
|
def __init__(self, models=("bge-m3:latest",), down=False, embed_exc=None, vector_value=0.01):
|
|
self.models = list(models)
|
|
self.down = down
|
|
self.embed_exc = embed_exc
|
|
self.vector_value = vector_value
|
|
self.tags_calls = 0
|
|
self.embed_calls = 0
|
|
|
|
|
|
class _FakeSession:
|
|
def __init__(self, backends: dict):
|
|
self._backends = backends
|
|
|
|
def _backend(self, url):
|
|
for base, backend in self._backends.items():
|
|
if url.startswith(base):
|
|
return backend
|
|
raise AssertionError(f"unexpected url: {url}")
|
|
|
|
def get(self, url, timeout=None):
|
|
backend = self._backend(url)
|
|
backend.tags_calls += 1
|
|
if backend.down:
|
|
return _FakeResponse(exc=aiohttp.ClientConnectionError("connection refused"))
|
|
return _FakeResponse({"models": [{"name": n} for n in backend.models]})
|
|
|
|
def post(self, url, json):
|
|
backend = self._backend(url)
|
|
backend.embed_calls += 1
|
|
if backend.down:
|
|
return _FakeResponse(exc=aiohttp.ClientConnectionError("connection refused"))
|
|
if backend.embed_exc is not None:
|
|
return _FakeResponse(exc=backend.embed_exc)
|
|
return _FakeResponse({"embedding": [backend.vector_value] * 1024})
|
|
|
|
|
|
class _FakeClock:
|
|
def __init__(self):
|
|
self.now = 1000.0
|
|
|
|
def __call__(self):
|
|
return self.now
|
|
|
|
|
|
def _router(fallback_url=FALLBACK, clock=None, **kwargs):
|
|
return EmbedRouter(
|
|
PRIMARY,
|
|
fallback_url,
|
|
embed_model="bge-m3",
|
|
clock=clock or _FakeClock(),
|
|
**kwargs,
|
|
)
|
|
|
|
|
|
class TestPrimaryHealthy:
|
|
async def test_embeds_on_primary_and_reports_its_name(self):
|
|
solaria = _FakeBackend()
|
|
piha = _FakeBackend()
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: piha})
|
|
embedding, backend = await _router().embed(session, "q")
|
|
assert backend == "solaria"
|
|
assert len(embedding) == 1024
|
|
assert solaria.embed_calls == 1
|
|
assert piha.embed_calls == 0
|
|
|
|
async def test_health_verdict_is_cached_within_ttl(self):
|
|
solaria = _FakeBackend()
|
|
clock = _FakeClock()
|
|
router = _router(clock=clock)
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: _FakeBackend()})
|
|
await router.embed(session, "q1")
|
|
probes_after_first = solaria.tags_calls # probe + first-use model verification
|
|
clock.now += 10 # inside the 30 s TTL
|
|
await router.embed(session, "q2")
|
|
assert solaria.tags_calls == probes_after_first # no new probe, model check done once
|
|
|
|
async def test_model_tag_with_latest_suffix_satisfies_bare_model_name(self):
|
|
solaria = _FakeBackend(models=["bge-m3:latest"])
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: _FakeBackend()})
|
|
_, backend = await _router().embed(session, "q")
|
|
assert backend == "solaria"
|
|
|
|
|
|
class TestFailover:
|
|
async def test_primary_down_at_probe_falls_back_to_piha(self):
|
|
solaria = _FakeBackend(down=True)
|
|
piha = _FakeBackend(vector_value=0.02)
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: piha})
|
|
embedding, backend = await _router().embed(session, "q")
|
|
assert backend == "piha"
|
|
assert embedding[0] == 0.02
|
|
assert solaria.embed_calls == 0
|
|
|
|
async def test_mid_embed_failure_serves_same_query_from_fallback(self):
|
|
# Plan §2 D2 step 3b: probe said up, the real embed then dies -- the SAME request
|
|
# must come back from the fallback, never as an error to the user.
|
|
solaria = _FakeBackend(embed_exc=aiohttp.ClientConnectionError("died mid-embed"))
|
|
piha = _FakeBackend(vector_value=0.02)
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: piha})
|
|
router = _router()
|
|
embedding, backend = await router.embed(session, "q")
|
|
assert backend == "piha"
|
|
assert embedding[0] == 0.02
|
|
assert solaria.embed_calls == 1
|
|
|
|
async def test_down_verdict_is_cached_and_skips_primary_until_ttl_expires(self):
|
|
solaria = _FakeBackend(down=True)
|
|
piha = _FakeBackend()
|
|
clock = _FakeClock()
|
|
router = _router(clock=clock)
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: piha})
|
|
await router.embed(session, "q1")
|
|
probes = solaria.tags_calls
|
|
clock.now += 10 # still inside TTL -> no re-probe, straight to fallback
|
|
_, backend = await router.embed(session, "q2")
|
|
assert backend == "piha"
|
|
assert solaria.tags_calls == probes
|
|
|
|
async def test_traffic_returns_to_primary_after_ttl_expiry(self):
|
|
# Test C from the task spec: SOLARIA comes back -> within one TTL window the
|
|
# router re-probes and routes to the GPU again.
|
|
solaria = _FakeBackend(down=True)
|
|
piha = _FakeBackend()
|
|
clock = _FakeClock()
|
|
router = _router(clock=clock)
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: piha})
|
|
_, backend = await router.embed(session, "q1")
|
|
assert backend == "piha"
|
|
solaria.down = False # SOLARIA wakes up
|
|
clock.now += 31 # TTL (30 s) expired
|
|
_, backend = await router.embed(session, "q2")
|
|
assert backend == "solaria"
|
|
|
|
|
|
class TestNoUsableBackend:
|
|
async def test_primary_down_without_fallback_raises_backend_error(self):
|
|
solaria = _FakeBackend(down=True)
|
|
session = _FakeSession({PRIMARY: solaria})
|
|
with pytest.raises(EmbedBackendError, match="no EMBED_FALLBACK_URL"):
|
|
await _router(fallback_url=None).embed(session, "q")
|
|
|
|
async def test_both_backends_down_raises_backend_error(self):
|
|
session = _FakeSession({PRIMARY: _FakeBackend(down=True), FALLBACK: _FakeBackend(down=True)})
|
|
with pytest.raises(EmbedBackendError, match="unreachable"):
|
|
await _router().embed(session, "q")
|
|
|
|
|
|
class TestModelInvariant:
|
|
async def test_fallback_without_bge_m3_is_a_loud_error_not_a_silent_embed(self):
|
|
solaria = _FakeBackend(down=True)
|
|
piha = _FakeBackend(models=["llama3:8b"])
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: piha})
|
|
with pytest.raises(ModelMismatchError, match="bge-m3"):
|
|
await _router().embed(session, "q")
|
|
assert piha.embed_calls == 0 # never embedded in the wrong vector space
|
|
|
|
async def test_primary_without_bge_m3_fails_over_to_verified_fallback(self):
|
|
solaria = _FakeBackend(models=["llama3:8b"])
|
|
piha = _FakeBackend()
|
|
session = _FakeSession({PRIMARY: solaria, FALLBACK: piha})
|
|
_, backend = await _router().embed(session, "q")
|
|
assert backend == "piha"
|
|
assert solaria.embed_calls == 0
|
|
|
|
|
|
class TestStatusReporting:
|
|
async def test_primary_status_up_and_fallback_status_up(self):
|
|
session = _FakeSession({PRIMARY: _FakeBackend(), FALLBACK: _FakeBackend()})
|
|
router = _router()
|
|
assert await router.primary_status(session) == "up"
|
|
assert await router.fallback_status(session) == "up"
|
|
|
|
async def test_fallback_status_unconfigured_without_fallback_url(self):
|
|
session = _FakeSession({PRIMARY: _FakeBackend()})
|
|
assert await _router(fallback_url=None).fallback_status(session) == "unconfigured"
|
|
|
|
async def test_primary_status_down_when_probe_fails(self):
|
|
session = _FakeSession({PRIMARY: _FakeBackend(down=True), FALLBACK: _FakeBackend()})
|
|
assert await _router().primary_status(session) == "down"
|