homelab-codex-ws/services/kb-query/tests/test_startup.py
oskar b2379e3275 feat(kb): add kb-query service skeleton (search API, no ingress yet)
Module 5 phase 4 step 1 (docs/kb/modules/05-faza4-plan.md, §4): first
user-facing HTTP entry point to the KB. FastAPI wrapping
kb_retrieval.cascade_query/flat_query — GET /search (query_text -> embed via
Ollama@SOLARIA -> cascade/flat -> envelope join -> JSON with per-source
links) and GET /healthz. Search API only, no answer synthesis (phase 5) and
no server-side dist filtering — the 0.45/0.55 colour thresholds are a
frontend concern (plan §7, a later step).

Hard startup invariant (plan §2 decision 2): refuses to start unless the
configured EMBED_MODEL is present in both document_chunk.model and
document_summary.embedding_model. Note the latter: document_summary.model is
the LLM that *wrote* the summary (claude-haiku-4-5/gemma3:12b), not the
embedder — checked live against kb-postgres@PIHA before writing this, see
app/startup.py's docstring. Verified end-to-end with a live docker run: the
invariant crash-loops on a mismatched EMBED_MODEL and passes through to a
real /search hit against the live corpus with a correct model.

Repo-only: no deploy, no npm/OIDC/DNS wiring (plan §8, later step), no local
embed fallback (plan §5, later step) — Ollama@SOLARIA is called directly and
a failure surfaces as 503, not a crash.

Also: scripts/deploy/deploy.sh's gate now builds each service via
`docker compose build` instead of a raw `docker build <svc_dir>`, so a
service whose docker-compose.yml declares a repo-root build context (needed
here to COPY packages/kb-retrieval/, the packages/ Dockerfile convention
already documented in CLAUDE.md) resolves the same way in the gate as it
does at real deploy time (deploy-node.sh's `docker compose ... up --build`).
No behavior change for existing single-context services — verified against
llm-gateway's compose file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 16:06:18 +02:00

57 lines
2.5 KiB
Python

"""Unit tests for the startup model invariant -- no real DB."""
from __future__ import annotations
import pathlib
import sys
import pytest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from app.startup import ModelInvariantError, validate_embed_model # noqa: E402
class _FakeConn:
def __init__(self, chunk_models: set, summary_embedding_models: set):
self._chunk_models = chunk_models
self._summary_embedding_models = summary_embedding_models
async def fetch(self, query, *params):
if "FROM document_chunk" in query:
return [{"model": m} for m in self._chunk_models]
if "FROM document_summary" in query:
return [{"embedding_model": m} for m in self._summary_embedding_models]
raise AssertionError(f"unexpected query: {query}")
class TestValidateEmbedModel:
async def test_passes_when_model_present_in_both_tables(self):
conn = _FakeConn(chunk_models={"bge-m3"}, summary_embedding_models={"bge-m3"})
await validate_embed_model(conn, "bge-m3") # must not raise
async def test_fails_when_chunk_model_missing(self):
conn = _FakeConn(chunk_models={"some-other-model"}, summary_embedding_models={"bge-m3"})
with pytest.raises(ModelInvariantError, match="document_chunk"):
await validate_embed_model(conn, "bge-m3")
async def test_fails_when_chunk_table_empty(self):
conn = _FakeConn(chunk_models=set(), summary_embedding_models={"bge-m3"})
with pytest.raises(ModelInvariantError, match="document_chunk"):
await validate_embed_model(conn, "bge-m3")
async def test_fails_when_summary_embedding_model_missing(self):
conn = _FakeConn(chunk_models={"bge-m3"}, summary_embedding_models={"some-other-model"})
with pytest.raises(ModelInvariantError, match="document_summary"):
await validate_embed_model(conn, "bge-m3")
async def test_does_not_confuse_summary_writer_model_with_embedding_model(self):
# Regression guard: document_summary.model is the LLM that WROTE the summary
# (claude-haiku-4-5/gemma3:12b), never bge-m3 -- checking that column instead of
# embedding_model would make this invariant impossible to satisfy.
conn = _FakeConn(
chunk_models={"bge-m3"},
summary_embedding_models={"bge-m3"},
)
assert conn._summary_embedding_models == {"bge-m3"}
await validate_embed_model(conn, "bge-m3") # must not raise