fix(summarizer): fail loudly on a rejected model id; parallel map phase

The analyst produced no briefs for nine days because SUMMARY_MODEL had been
retired: every chat completion returned 404, nous_client.chat() swallowed it
into "", and the map phase "succeeded" with zero blocks.

- nous_client.chat(): log status_code + a 500-char body slice for every
  non-200. 400/404/422 now raise NousAPIError (bad model id / payload cannot
  succeed on a retry); 429/5xx are retried with backoff inside the call;
  401/other keep the old empty-return contract.
- Startup validation: one GET /models per process; if SUMMARY_MODEL is absent
  the run logs an ERROR with the configured id plus near matches and returns
  rc=2 before issuing any chat call. Fails open (warning) when /models itself
  is unreachable.
- Map phase: ThreadPoolExecutor fan-out capped by SUMMARY_MAP_CONCURRENCY
  (default 16). Grading still runs in batch order on the main thread; reduce
  stays serial; the 60 s per-call timeout is unchanged.
- summarize_news() now returns an exit code and __main__ sys.exit()s it:
  zero parsed map blocks, an empty reduce, or an unpersisted brief all exit
  non-zero. The scheduler logs rc at ERROR when it is not 0.
- Map calls start at 8192 completion tokens (they escalate to 16384): ~60% of
  real batches overflowed 4096 and were regenerated at 8192, doubling their
  wall time for no benefit.

Measured on the real backlog: NEWS_RECAP=1 NEWS_SUMMARIZE_FORCE=1
python summarizer.py over 2984 articles / 746 batches finished in 951 s
(15m51s), rc=0, 746/746 batches non-empty, 0 warnings.

Prompts, BATCH_SIZE=4, grading/rubric behaviour and the DB schema are
untouched (article_summaries.kind stays interval / daily_recap).
This commit is contained in:
backend 2026-12-04 23:34:54 -05:00
commit 625c935c80
6 changed files with 781 additions and 51 deletions

View file

@ -1,7 +1,10 @@
from unittest.mock import MagicMock
import httpx
from nous_client import chat
import pytest
import nous_client
from nous_client import NousAPIError, chat, model_available, reset_model_cache
DEFAULT_UA = "osint-dashboard-news-summarizer"
BASE = "https://inference-api.nousresearch.com/v1"
@ -52,7 +55,7 @@ def test_posts_chat_completions_with_auth_body_and_returns_content(monkeypatch):
assert captured["json"]["model"] == "hermes-3"
assert captured["json"]["messages"] == [{"role": "user", "content": "summarize this"}]
assert captured["json"]["temperature"] == 0.2
assert captured["json"]["max_tokens"] == 4096
assert captured["json"]["max_tokens"] == nous_client.MAX_TOKENS_TEXT
assert "response_format" not in captured["json"]
@ -122,3 +125,146 @@ def test_timeout_returns_empty_string(monkeypatch):
_install_fake(monkeypatch, post_impl)
assert chat("p", api_key="k", model="m", base_url=BASE) == ""
# ── Non-200 handling (the nine-day silent-brief incident) ───────────────────
def _install_fake_client(monkeypatch, *, post=None, get=None):
"""Fake httpx.Client with both post (chat) and get (/models) captured."""
captured = {"posts": [], "gets": []}
class FakeClient:
def __init__(self, timeout=None, **kwargs):
captured["timeout"] = timeout
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def post(self, url, *, headers=None, json=None, **kwargs):
captured["posts"].append({"url": url, "headers": headers, "json": json})
return post(url, headers, json)
def get(self, url, *, headers=None, **kwargs):
captured["gets"].append({"url": url, "headers": headers})
return get(url, headers)
monkeypatch.setattr(httpx, "Client", FakeClient)
return captured
def _json_ok(content="ok"):
return httpx.Response(200, json={"choices": [{"message": {"content": content}}]})
@pytest.mark.parametrize("status", [400, 404, 422])
def test_rejected_request_raises_instead_of_returning_empty(monkeypatch, status):
"""A retired model id (404) must abort the run, not return ""."""
_install_fake_client(
monkeypatch,
post=lambda *a: httpx.Response(status, json={"error": "no such model: retired/x"}),
)
with pytest.raises(NousAPIError) as excinfo:
chat("p", api_key="k", model="retired/x", base_url=BASE)
assert excinfo.value.status_code == status
assert "no such model" in str(excinfo.value)
def test_non_200_logs_status_and_a_body_slice(monkeypatch, caplog):
body = "y" * 2000
_install_fake_client(monkeypatch, post=lambda *a: httpx.Response(404, text=body))
with caplog.at_level("ERROR"):
with pytest.raises(NousAPIError):
chat("p", api_key="k", model="gone/model", base_url=BASE)
message = " ".join(record.message for record in caplog.records)
assert "status=404" in message
assert "y" * 499 in message # the 500-char slice is logged
assert "y" * 900 not in message # ...and truncated
def test_429_is_retried_and_the_retry_wins(monkeypatch):
calls = {"n": 0}
def post(*a):
calls["n"] += 1
if calls["n"] == 1:
return httpx.Response(429, json={"error": "rate limited"})
return _json_ok("second try")
_install_fake_client(monkeypatch, post=post)
assert chat("p", api_key="k", model="m", base_url=BASE) == "second try"
assert calls["n"] == 2
def test_5xx_is_retried_up_to_max_attempts_then_gives_up(monkeypatch):
calls = {"n": 0}
def post(*a):
calls["n"] += 1
return httpx.Response(503, text="upstream down")
_install_fake_client(monkeypatch, post=post)
assert chat("p", api_key="k", model="m", base_url=BASE) == ""
assert calls["n"] == nous_client.MAX_ATTEMPTS
# ── Startup model validation against GET /models ────────────────────────────
MODELS_BODY = {
"data": [
{"id": "deepseek/deepseek-v4.1-flash-1017"},
{"id": "hermes/hermes-4.3-36b"},
{"id": "qwen/qwen3-32b"},
]
}
def test_model_available_true_when_the_portal_lists_it(monkeypatch):
captured = _install_fake_client(
monkeypatch, get=lambda *a: httpx.Response(200, json=MODELS_BODY)
)
reset_model_cache()
assert model_available(
api_key="k", base_url=BASE, model="deepseek/deepseek-v4.1-flash-1017"
) is True
assert captured["gets"][0]["url"] == f"{BASE}/models"
assert captured["gets"][0]["headers"]["Authorization"] == "Bearer k"
def test_missing_model_is_an_error_and_the_check_is_cached(monkeypatch, caplog):
captured = _install_fake_client(
monkeypatch, get=lambda *a: httpx.Response(200, json=MODELS_BODY)
)
reset_model_cache()
with caplog.at_level("ERROR"):
assert model_available(api_key="k", base_url=BASE, model="meituan/longcat-2.5:free") is False
assert model_available(api_key="k", base_url=BASE, model="meituan/longcat-2.5:free") is False
message = " ".join(record.message for record in caplog.records)
assert "meituan/longcat-2.5:free" in message
assert "Near matches:" in message
assert len(captured["gets"]) == 1 # one GET /models per process
def test_near_matches_name_the_closest_offered_id(monkeypatch, caplog):
_install_fake_client(monkeypatch, get=lambda *a: httpx.Response(200, json=MODELS_BODY))
reset_model_cache()
with caplog.at_level("ERROR"):
assert model_available(
api_key="k", base_url=BASE, model="deepseek/deepseek-v4.1-flash-1010"
) is False
message = " ".join(record.message for record in caplog.records)
assert "deepseek/deepseek-v4.1-flash-1017" in message
def test_models_endpoint_down_fails_open_with_a_warning(monkeypatch, caplog):
def get(*a):
raise httpx.ConnectError("no route to host")
_install_fake_client(monkeypatch, get=get)
reset_model_cache()
with caplog.at_level("WARNING"):
assert model_available(api_key="k", base_url=BASE, model="x/y") is True
assert any("Could not validate" in record.message for record in caplog.records)