"""Pure-stdlib tests for the Ollama System One decision engine provider. The engine is exercised over a real loopback HTTP server (the transport is not mocked): the handler records requests and returns canned ollama ``/api/version``, ``/api/show``, and ``/v1/systemone`` responses, so the tests prove the decision-contract mapping, the ollama-specific probing, and the strict distribution validation. No model, no GGUF, no external network. """ from __future__ import annotations import json import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import pytest from semif_agent.decisions import DecisionRequest, Option from semif_agent.engine import EngineUnavailable from semif_agent.ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine class _Handler(BaseHTTPRequestHandler): def log_message(self, *args): # keep the test output quiet pass def _read(self) -> dict: length = int(self.headers.get("content-length", 0) or 0) raw = self.rfile.read(length) if length else b"{}" return json.loads(raw or b"{}") def _send(self, status: int, payload: dict) -> None: body = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("content-type", "application/json") self.send_header("content-length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self): self.server.state.setdefault("gets", []).append(self.path) if self.path == "/api/version": self._send( self.server.state.get("version_status", 200), {"version": "0.40.13"}, ) else: self._send(404, {"error": "not found"}) def do_POST(self): body = self._read() self.server.state.setdefault("requests", []).append( (self.path, body, {k.lower(): v for k, v in self.headers.items()}) ) if self.path == "/api/show": status = self.server.state.get("show_status", 200) response = self.server.state.get("show_response") if response is None: response = _default_show() self._send(status, response) elif self.path == "/v1/systemone": status = self.server.state.get("systemone_status", 200) response = self.server.state.get("systemone_response") if response is None: response = _default_systemone(body) self._send(status, response) else: self._send(404, {"error": "not found"}) def _default_show() -> dict: return { "model": "clef-flash", "parameters": "num_ctx 16384", "capabilities": ["decision"], "model_info": {"clef.context_length": 262144}, } def _default_systemone(body: dict) -> dict: criteria = body["questions"]["decision"]["criteria"] keys = list(criteria) probs = { key: (0.9 if index == 0 else 0.1 / max(len(keys) - 1, 1)) for index, key in enumerate(keys) } # Return the keys in REVERSE order to prove the engine aligns by id, not by # position in the returned object. return { "model": "clef-flash", "answers": { "decision": { "type": "choice", "choice": keys[0], "probabilities": dict(reversed(list(probs.items()))), "confidence": 0.8, } }, "usage": {"input_tokens": 42, "output_tokens": 1}, } @pytest.fixture() def ollama(): server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) server.state = {} thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() base = f"http://127.0.0.1:{server.server_address[1]}" yield server, base server.shutdown() server.server_close() def _engine(base: str, **cfg) -> OllamaSystemOneEngine: return OllamaSystemOneEngine( OllamaSystemOneConfig(base_url=base, model="clef-flash", timeout=5.0, **cfg) ) def _decision(*option_ids: str) -> DecisionRequest: return DecisionRequest( state="the user said hello", question="Which category handles this request?", options=[Option(oid, f"description for {oid}") for oid in option_ids], ) def test_call_maps_decision_to_a_choice_question(ollama): server, base = ollama result = _engine(base).call(_decision("response", "calendar")) assert result.option_ids == ["response", "calendar"] assert result.prob("response") == pytest.approx(0.9) assert result.prob("calendar") == pytest.approx(0.1) assert result.selected == "response" assert result.extra["input_tokens"] == 42 assert result.extra["choice"] == "response" assert result.extra["confidence"] == 0.8 assert result.extra["served_model"] == "clef-flash" path, body, _ = server.state["requests"][-1] assert path == "/v1/systemone" assert body["model"] == "clef-flash" assert body["state"] == "the user said hello" question = body["questions"]["decision"] assert question["type"] == "choice" assert question["instructions"] == "Which category handles this request?" assert question["criteria"] == { "response": "description for response", "calendar": "description for calendar", } # keep_alive is omitted unless configured. assert "keep_alive" not in body def test_call_sends_a_configured_keep_alive(ollama): server, base = ollama _engine(base, keep_alive="5m").call(_decision("a", "b")) _, body, _ = server.state["requests"][-1] assert body["keep_alive"] == "5m" def test_call_sends_null_for_a_bare_label(ollama): server, base = ollama request = DecisionRequest( state="state", question="question", options=[Option("a", ""), Option("b", " ")], ) _engine(base).call(request) _, body, _ = server.state["requests"][-1] assert body["questions"]["decision"]["criteria"] == {"a": None, "b": None} def test_call_normalizes_an_unnormalized_distribution(ollama): server, base = ollama server.state["systemone_response"] = { "answers": {"decision": {"type": "choice", "probabilities": {"a": 0.4, "b": 0.4}}} } result = _engine(base).call(_decision("a", "b")) assert result.probs == pytest.approx({"a": 0.5, "b": 0.5}) def test_call_rejects_mismatched_probability_keys(ollama): server, base = ollama server.state["systemone_response"] = { "answers": {"decision": {"type": "choice", "probabilities": {"a": 1.0}}} } with pytest.raises(EngineUnavailable): _engine(base).call(_decision("a", "b")) def test_call_rejects_a_choice_outside_the_requested_options(ollama): server, base = ollama server.state["systemone_response"] = { "answers": { "decision": { "type": "choice", "choice": "other", "probabilities": {"a": 0.8, "b": 0.2}, } } } with pytest.raises(EngineUnavailable): _engine(base).call(_decision("a", "b")) def test_call_rejects_all_zero_distribution(ollama): server, base = ollama server.state["systemone_response"] = { "answers": {"decision": {"type": "choice", "probabilities": {"a": 0.0, "b": 0.0}}} } with pytest.raises(EngineUnavailable): _engine(base).call(_decision("a", "b")) def test_call_rejects_out_of_range_probability(ollama): server, base = ollama server.state["systemone_response"] = { "answers": {"decision": {"type": "choice", "probabilities": {"a": 1.5, "b": 0.5}}} } with pytest.raises(EngineUnavailable): _engine(base).call(_decision("a", "b")) def test_call_rejects_http_error_with_the_ollama_error_body(ollama): server, base = ollama server.state["systemone_status"] = 400 with pytest.raises(EngineUnavailable, match="400"): _engine(base).call(_decision("a", "b")) def test_call_rejects_missing_answer(ollama): server, base = ollama server.state["systemone_response"] = {"answers": {}} with pytest.raises(EngineUnavailable): _engine(base).call(_decision("a", "b")) def test_call_requires_at_least_two_options(ollama): _, base = ollama with pytest.raises(EngineUnavailable): _engine(base).call(_decision("a")) def test_call_requires_a_non_empty_state(ollama): _, base = ollama request = DecisionRequest( state=" ", question="q", options=[Option("a", "a"), Option("b", "b")], ) with pytest.raises(EngineUnavailable): _engine(base).call(request) def test_call_sends_bearer_token(ollama): server, base = ollama _engine(base, api_key="secret").call(_decision("a", "b")) _, _, headers = server.state["requests"][-1] assert headers.get("authorization") == "Bearer secret" def test_generate_is_unavailable(ollama): _, base = ollama with pytest.raises(EngineUnavailable): _engine(base).generate([{"role": "user", "content": "hi"}]) def test_warm_probes_ollama_native_endpoints_and_marks_loaded(ollama): server, base = ollama engine = _engine(base, context_tokens=0) assert engine.loaded is False engine.warm() assert engine.loaded is True assert "/api/version" in server.state["gets"] assert [path for path, _, _ in server.state["requests"]] == ["/api/show"] # context_tokens=0 follows the model's real num_ctx from /api/show. assert engine.context_tokens == 16384 def test_warm_falls_back_to_the_architecture_context_length(ollama): server, base = ollama server.state["show_response"] = { "capabilities": ["decision"], "parameters": "", "model_info": {"clef.context_length": 8192}, } engine = _engine(base, context_tokens=0) engine.warm() assert engine.context_tokens == 8192 def test_warm_keeps_an_explicit_context_window(ollama): server, base = ollama engine = _engine(base, context_tokens=4096) engine.warm() assert engine.context_tokens == 4096 def test_warm_rejects_a_model_without_the_decision_capability(ollama): server, base = ollama server.state["show_response"] = { "capabilities": ["completion", "thinking"], "parameters": "num_ctx 4096", } with pytest.raises(EngineUnavailable, match="decision"): _engine(base).warm() def test_warm_rejects_a_missing_model(ollama): server, base = ollama server.state["show_status"] = 404 with pytest.raises(EngineUnavailable): _engine(base).warm() def test_warm_rejects_an_unreachable_server(): engine = OllamaSystemOneEngine( OllamaSystemOneConfig( base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0 ) ) with pytest.raises(EngineUnavailable): engine.warm() def test_unreachable_endpoint_raises_engine_unavailable(): engine = OllamaSystemOneEngine( OllamaSystemOneConfig( base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0 ) ) with pytest.raises(EngineUnavailable): engine.call(_decision("a", "b"))