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:
parent
6066ac8e0d
commit
625c935c80
6 changed files with 781 additions and 51 deletions
|
|
@ -1,11 +1,37 @@
|
|||
"""Keep summarizer unit tests importable without Postgres drivers."""
|
||||
"""Keep summarizer unit tests importable without Postgres drivers, offline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
_SUMMERIZER_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_SUMMERIZER_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_SUMMERIZER_DIR))
|
||||
|
||||
if "psycopg2" not in sys.modules:
|
||||
fake = ModuleType("psycopg2")
|
||||
fake.connect = lambda **kwargs: None # type: ignore[attr-defined]
|
||||
sys.modules["psycopg2"] = fake
|
||||
|
||||
import pytest # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def offline_llm_defaults(monkeypatch):
|
||||
"""No network and no retry sleeps unless a test asks for them.
|
||||
|
||||
``summarize_news()`` validates SUMMARY_MODEL against ``GET /models`` once
|
||||
per process; unit tests must never leave the box for it. Tests that
|
||||
exercise the missing-model path patch ``summarizer.model_available``
|
||||
themselves (a later ``setattr`` wins over this one).
|
||||
"""
|
||||
import nous_client
|
||||
import summarizer
|
||||
|
||||
monkeypatch.setenv("NOUS_RETRY_BACKOFF_S", "0")
|
||||
nous_client.reset_model_cache()
|
||||
monkeypatch.setattr(summarizer, "model_available", lambda **kwargs: True)
|
||||
yield
|
||||
nous_client.reset_model_cache()
|
||||
|
|
|
|||
233
news/summerizer/tests/test_map_concurrency.py
Normal file
233
news/summerizer/tests/test_map_concurrency.py
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
"""Parallel map phase: bounded fan-out, ordered grading, loud failures."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import nous_client
|
||||
import summarizer
|
||||
|
||||
|
||||
REDUCE_REPLY = json.dumps(
|
||||
{"summary_en": "Brief over the batch facts.", "ticker": [], "map_items": []}
|
||||
)
|
||||
|
||||
|
||||
def _articles(n: int) -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"id": i + 1,
|
||||
"title": f"Story {i + 1}",
|
||||
"content": f"Body of story {i + 1} " + "x" * 200,
|
||||
"url": f"https://ex.com/{i + 1}",
|
||||
"domain": "ex.com",
|
||||
}
|
||||
for i in range(n)
|
||||
]
|
||||
|
||||
|
||||
def _map_reply(batch_size: int, score: int = 90) -> str:
|
||||
"""One well-formed graded block per article in a batch (numbering restarts)."""
|
||||
blocks = []
|
||||
for n in range(1, batch_size + 1):
|
||||
blocks.append(
|
||||
"\n".join(
|
||||
[
|
||||
f"Article {n}:",
|
||||
"- Fact bullet one",
|
||||
f"- Score: {score}",
|
||||
"- Location: Kyiv",
|
||||
"- Entities: None",
|
||||
"- Category: politics",
|
||||
"- OSINT signal: No notable OSINT signal.",
|
||||
"- Lat: 50.45",
|
||||
"- Lon: 30.52",
|
||||
]
|
||||
)
|
||||
)
|
||||
return "\n\n".join(blocks)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offline_run(monkeypatch):
|
||||
"""Install a summarize_news() run with DB, credentials and persistence stubbed."""
|
||||
|
||||
def install(
|
||||
*,
|
||||
articles,
|
||||
call_llm,
|
||||
batch_size=4,
|
||||
concurrency=8,
|
||||
model_ok=True,
|
||||
save_id=7,
|
||||
):
|
||||
monkeypatch.setenv("NOUS_API_KEY", "test-key")
|
||||
monkeypatch.setenv("SUMMARY_MODEL", "test/model")
|
||||
monkeypatch.setenv("SUMMARY_MAP_CONCURRENCY", str(concurrency))
|
||||
monkeypatch.setattr(summarizer, "BATCH_SIZE", batch_size)
|
||||
monkeypatch.setattr(summarizer, "call_llm", call_llm)
|
||||
monkeypatch.setattr(summarizer, "model_available", lambda **kwargs: model_ok)
|
||||
monkeypatch.setattr(summarizer, "ensure_tables", lambda: None)
|
||||
monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: articles)
|
||||
monkeypatch.setattr(summarizer, "_already_recapped_today", lambda: False)
|
||||
monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False)
|
||||
monkeypatch.setattr(summarizer, "save_batch", lambda *a, **k: save_id)
|
||||
monkeypatch.setattr(summarizer, "persist_article_scores", lambda *a, **k: None)
|
||||
|
||||
return install
|
||||
|
||||
|
||||
# ── Failure paths ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_missing_model_skips_the_run_without_a_single_chat_call(offline_run):
|
||||
calls: list = []
|
||||
offline_run(
|
||||
articles=_articles(12),
|
||||
call_llm=lambda *a, **k: calls.append(a) or "",
|
||||
model_ok=False,
|
||||
)
|
||||
assert summarizer.summarize_news() == 2
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_all_map_batches_empty_exits_non_zero(offline_run, caplog):
|
||||
reduce_calls: list = []
|
||||
|
||||
def fake_llm(prompt, *, json_mode=False, **kwargs):
|
||||
if json_mode:
|
||||
reduce_calls.append(prompt)
|
||||
return REDUCE_REPLY
|
||||
return ""
|
||||
|
||||
offline_run(articles=_articles(12), call_llm=fake_llm)
|
||||
with caplog.at_level("ERROR"):
|
||||
assert summarizer.summarize_news() == 1
|
||||
assert reduce_calls == [] # never reduce over an empty map
|
||||
assert any("no article blocks" in record.message for record in caplog.records)
|
||||
|
||||
|
||||
def test_non_retryable_api_error_exits_non_zero(offline_run, caplog):
|
||||
def fake_llm(prompt, *, json_mode=False, **kwargs):
|
||||
raise nous_client.NousAPIError(
|
||||
404, '{"error":"model not found"}', "https://x/v1/chat/completions"
|
||||
)
|
||||
|
||||
offline_run(articles=_articles(8), call_llm=fake_llm)
|
||||
with caplog.at_level("ERROR"):
|
||||
assert summarizer.summarize_news() == 1
|
||||
assert any("404" in record.message for record in caplog.records)
|
||||
|
||||
|
||||
def test_reduce_returning_empty_exits_non_zero(offline_run):
|
||||
def fake_llm(prompt, *, json_mode=False, **kwargs):
|
||||
return "" if json_mode else _map_reply(4)
|
||||
|
||||
offline_run(articles=_articles(8), call_llm=fake_llm)
|
||||
assert summarizer.summarize_news() == 1
|
||||
|
||||
|
||||
def test_unpersisted_brief_exits_non_zero(offline_run):
|
||||
def fake_llm(prompt, *, json_mode=False, **kwargs):
|
||||
return REDUCE_REPLY if json_mode else _map_reply(4)
|
||||
|
||||
offline_run(articles=_articles(8), call_llm=fake_llm, save_id=None)
|
||||
assert summarizer.summarize_news() == 1
|
||||
|
||||
|
||||
def test_successful_run_exits_zero(offline_run):
|
||||
def fake_llm(prompt, *, json_mode=False, **kwargs):
|
||||
return REDUCE_REPLY if json_mode else _map_reply(4)
|
||||
|
||||
offline_run(articles=_articles(8), call_llm=fake_llm)
|
||||
assert summarizer.summarize_news() == 0
|
||||
|
||||
|
||||
# ── Concurrency ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_concurrency_cap_is_honoured(offline_run):
|
||||
state = {"in_flight": 0, "peak": 0, "calls": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
def fake_llm(prompt, *, json_mode=False, **kwargs):
|
||||
if json_mode:
|
||||
return REDUCE_REPLY
|
||||
with lock:
|
||||
state["in_flight"] += 1
|
||||
state["calls"] += 1
|
||||
state["peak"] = max(state["peak"], state["in_flight"])
|
||||
time.sleep(0.02)
|
||||
with lock:
|
||||
state["in_flight"] -= 1
|
||||
return _map_reply(4)
|
||||
|
||||
offline_run(articles=_articles(24), call_llm=fake_llm, batch_size=4, concurrency=3)
|
||||
assert summarizer.summarize_news() == 0
|
||||
assert state["calls"] == 6
|
||||
assert state["peak"] == 3 # the cap is actually used…
|
||||
assert state["in_flight"] == 0 # …and never exceeded
|
||||
|
||||
|
||||
def test_map_concurrency_env_override(monkeypatch):
|
||||
monkeypatch.setenv("SUMMARY_MAP_CONCURRENCY", "16")
|
||||
assert summarizer.map_concurrency() == 16
|
||||
monkeypatch.setenv("SUMMARY_MAP_CONCURRENCY", "0")
|
||||
assert summarizer.map_concurrency() == 1
|
||||
monkeypatch.delenv("SUMMARY_MAP_CONCURRENCY", raising=False)
|
||||
assert summarizer.DEFAULT_SUMMARY_MAP_CONCURRENCY == 16
|
||||
assert summarizer.map_concurrency() == 16
|
||||
|
||||
|
||||
def test_map_phase_grades_in_batch_order_despite_out_of_order_finishes(monkeypatch):
|
||||
"""Batch 0 finishes last; results must still come back indexed 0..n-1."""
|
||||
articles = _articles(16)
|
||||
monkeypatch.setattr(summarizer, "BATCH_SIZE", 4)
|
||||
monkeypatch.setenv("SUMMARY_MAP_CONCURRENCY", "4")
|
||||
|
||||
def fake_llm(prompt, *, api_key, model, base_url, json_mode=False):
|
||||
first_article = int(re.search(r"Story (\d+)", prompt).group(1))
|
||||
batch_index = (first_article - 1) // 4
|
||||
time.sleep(0.05 if batch_index == 0 else 0.005)
|
||||
return f"reply-{batch_index}"
|
||||
|
||||
monkeypatch.setattr(summarizer, "call_llm", fake_llm)
|
||||
mapped, empty, total = summarizer.map_phase(
|
||||
articles, api_key="k", model="m", base_url="https://x/v1"
|
||||
)
|
||||
assert (empty, total) == (0, 4)
|
||||
assert mapped == [(0, "reply-0"), (1, "reply-1"), (2, "reply-2"), (3, "reply-3")]
|
||||
|
||||
|
||||
def test_map_phase_counts_empty_batches(monkeypatch):
|
||||
monkeypatch.setattr(summarizer, "BATCH_SIZE", 4)
|
||||
monkeypatch.setenv("SUMMARY_MAP_CONCURRENCY", "2")
|
||||
monkeypatch.setattr(
|
||||
summarizer, "call_llm", lambda prompt, **kwargs: "" if "Story 5" in prompt else "ok"
|
||||
)
|
||||
mapped, empty, total = summarizer.map_phase(
|
||||
_articles(8), api_key="k", model="m", base_url="https://x/v1"
|
||||
)
|
||||
assert (empty, total) == (1, 2)
|
||||
assert [index for index, _ in mapped] == [0]
|
||||
|
||||
|
||||
def test_map_phase_cancels_queued_batches_on_hard_error(monkeypatch):
|
||||
"""A 404 mid-flight raises and does not keep posting the remaining batches."""
|
||||
monkeypatch.setattr(summarizer, "BATCH_SIZE", 4)
|
||||
monkeypatch.setenv("SUMMARY_MAP_CONCURRENCY", "1")
|
||||
posts = {"n": 0}
|
||||
|
||||
def fake_llm(prompt, **kwargs):
|
||||
posts["n"] += 1
|
||||
raise nous_client.NousAPIError(404, "gone", "https://x/v1/chat/completions")
|
||||
|
||||
monkeypatch.setattr(summarizer, "call_llm", fake_llm)
|
||||
with pytest.raises(nous_client.NousAPIError):
|
||||
summarizer.map_phase(_articles(40), api_key="k", model="m", base_url="https://x/v1")
|
||||
assert posts["n"] < 10 # 10 batches exist; the run stopped at the first failure
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Reference in a new issue