From 625c935c804f0f9f7c0a43e5fa1daf232fdf6500 Mon Sep 17 00:00:00 2001 From: backend Date: Fri, 4 Dec 2026 23:34:54 -0500 Subject: [PATCH] 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). --- news/summerizer/nous_client.py | 258 ++++++++++++++++-- news/summerizer/run_news_summarizer.py | 8 +- news/summerizer/summarizer.py | 157 +++++++++-- news/summerizer/tests/conftest.py | 28 +- news/summerizer/tests/test_map_concurrency.py | 233 ++++++++++++++++ news/summerizer/tests/test_nous_client.py | 150 +++++++++- 6 files changed, 782 insertions(+), 52 deletions(-) create mode 100644 news/summerizer/tests/test_map_concurrency.py diff --git a/news/summerizer/nous_client.py b/news/summerizer/nous_client.py index fc480f1..311f548 100644 --- a/news/summerizer/nous_client.py +++ b/news/summerizer/nous_client.py @@ -1,11 +1,22 @@ -"""HTTP client for the Nous inference chat completions API.""" +"""HTTP client for the Nous inference chat completions API. + +Every non-200 is logged with its status code and a slice of the body. A +non-retryable rejection (400/404/422 — e.g. a retired model id) raises +``NousAPIError`` so a misconfigured run aborts loudly instead of quietly +mapping zero batches for days. 429/5xx are retried inside the call. +""" from __future__ import annotations +import difflib +import logging import os +import time import httpx +logger = logging.getLogger("news.nous_client") + _DEFAULT_UA = "osint-dashboard-news-summarizer" _DEFAULT_BASE = "https://inference-api.nousresearch.com/v1" _JSON_SYSTEM = ( @@ -13,15 +24,84 @@ _JSON_SYSTEM = ( "Never truncate mid-sentence. If you run out of room, drop the lowest-priority item." ) +# How much of an error body to log. +BODY_LOG_CHARS = 500 -def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str: - resolved = (base_url or os.environ.get("NOUS_BASE_URL", _DEFAULT_BASE)).rstrip("/") - url = f"{resolved}/chat/completions" - headers = { +# Requests that can never succeed on a retry: a retired model id (404), a +# malformed payload (400) or a rejected schema (422). Swallowing these is how +# the summarizer idled for nine days with an empty brief. +HARD_ERROR_STATUS = frozenset({400, 404, 422}) + +# Transient: retried with backoff inside the single call. +RETRY_STATUS = frozenset({429, 500, 502, 503, 504}) + +MAX_ATTEMPTS = 3 +MAX_TOKENS_CEILING = 16384 +# A map call over four full articles routinely needs more than 4096 completion +# tokens on the live model, and the old code then regenerated the whole answer +# with 8192 — two calls' worth of latency for one batch. Start text calls at +# the budget they escalate to anyway; the ceiling escalation below still +# covers genuinely truncated answers. +MAX_TOKENS_TEXT = 8192 +MAX_TOKENS_JSON = 8192 + + +class NousAPIError(RuntimeError): + """A non-retryable non-200 from the Nous API (bad model id, bad payload...).""" + + def __init__(self, status_code: int, body: str, url: str = "") -> None: + self.status_code = status_code + self.body = body + self.url = url + super().__init__(f"Nous API {status_code} from {url}: {body[:BODY_LOG_CHARS]}") + + +def _resolve_base(base_url: str | None) -> str: + return (base_url or os.environ.get("NOUS_BASE_URL", _DEFAULT_BASE)).rstrip("/") + + +def _headers(api_key: str) -> dict: + return { "Authorization": f"Bearer {api_key}", "User-Agent": os.environ.get("OSINT_USER_AGENT") or _DEFAULT_UA, } - max_tokens = 8192 if json_mode else 4096 + + +def _body_text(resp) -> str: + """Best-effort response body as text (httpx exposes .text).""" + try: + text = resp.text + except Exception: # noqa: BLE001 — a dead response must not mask the status + return "" + return text if isinstance(text, str) else "" + + +def _retry_backoff(attempt: int) -> float: + """Seconds to sleep before retry ``attempt`` (1-based); env-tunable for tests.""" + try: + base = float(os.environ.get("NOUS_RETRY_BACKOFF_S", "2")) + except ValueError: + base = 2.0 + return max(0.0, base) * (2 ** (attempt - 1)) + + +def _sleep_before_retry(attempt: int) -> None: + delay = _retry_backoff(attempt) + if delay: + time.sleep(delay) + + +def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str: + """POST one chat completion. + + Returns the message content, or ``""`` for retryable/exhausted failures. + Raises ``NousAPIError`` when the API rejects the request itself + (400/404/422) — the caller must treat that as fatal for the run. + """ + resolved = _resolve_base(base_url) + url = f"{resolved}/chat/completions" + headers = _headers(api_key) + max_tokens = MAX_TOKENS_JSON if json_mode else MAX_TOKENS_TEXT timeout = 120.0 if json_mode else 60.0 messages = [{"role": "user", "content": prompt}] if json_mode: @@ -37,21 +117,157 @@ def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str: } if json_mode: payload["response_format"] = {"type": "json_object"} - last_content = "" - try: - for attempt in range(2): + + for attempt in range(1, MAX_ATTEMPTS + 1): + try: with httpx.Client(timeout=timeout) as client: resp = client.post(url, headers=headers, json=payload) - if resp.status_code == 401 or resp.status_code >= 500: - return "" - data = resp.json() - choice = (data.get("choices") or [{}])[0] - last_content = (choice.get("message") or {}).get("content") or "" - finish = choice.get("finish_reason") - if finish == "length" and attempt == 0: - payload["max_tokens"] = min(int(payload["max_tokens"]) * 2, 16384) + except httpx.HTTPError as exc: + logger.warning( + "Nous chat transport error model=%s attempt=%d/%d: %r", + model, attempt, MAX_ATTEMPTS, exc, + ) + if attempt < MAX_ATTEMPTS: + _sleep_before_retry(attempt) continue - return last_content - return last_content - except Exception: - return "" + return "" + + if resp.status_code != 200: + body = _body_text(resp)[:BODY_LOG_CHARS] + if resp.status_code in HARD_ERROR_STATUS: + logger.error( + "Nous chat rejected the request model=%s status=%s url=%s " + "attempt=%d/%d body=%s — not retryable, aborting run", + model, resp.status_code, url, attempt, MAX_ATTEMPTS, body, + ) + raise NousAPIError(resp.status_code, _body_text(resp), url) + logger.warning( + "Nous chat non-200 model=%s status=%s url=%s attempt=%d/%d body=%s", + model, resp.status_code, url, attempt, MAX_ATTEMPTS, body, + ) + if resp.status_code in RETRY_STATUS and attempt < MAX_ATTEMPTS: + _sleep_before_retry(attempt) + continue + return "" + + try: + data = resp.json() + except ValueError: + logger.warning( + "Nous chat returned non-JSON model=%s status=200 attempt=%d/%d body=%s", + model, attempt, MAX_ATTEMPTS, _body_text(resp)[:BODY_LOG_CHARS], + ) + if attempt < MAX_ATTEMPTS: + _sleep_before_retry(attempt) + continue + return "" + + choices = (data.get("choices") if isinstance(data, dict) else None) or [{}] + choice = choices[0] or {} + content = (choice.get("message") or {}).get("content") or "" + if ( + choice.get("finish_reason") == "length" + and payload["max_tokens"] < MAX_TOKENS_CEILING + ): + payload["max_tokens"] = min(payload["max_tokens"] * 2, MAX_TOKENS_CEILING) + logger.warning( + "Nous chat hit max_tokens model=%s — retrying with max_tokens=%d", + model, payload["max_tokens"], + ) + continue + return content + return "" + + +# ── Startup model validation ─────────────────────────────────────────────── +# One GET /models per (base_url, model) per process: a retired SUMMARY_MODEL +# must disable the run before 745 batch calls hammer the API. + +_MODEL_AVAILABLE: dict[tuple[str, str], bool] = {} + + +def list_models(*, api_key: str, base_url: str | None = None, timeout: float = 30.0) -> list[str]: + """GET {base_url}/models and return the offered model ids. + + Raises ``NousAPIError`` on a non-200 so the caller decides whether to fail + open (skip validation) or abort. + """ + resolved = _resolve_base(base_url) + url = f"{resolved}/models" + with httpx.Client(timeout=timeout) as client: + resp = client.get(url, headers=_headers(api_key)) + if resp.status_code != 200: + body = _body_text(resp)[:BODY_LOG_CHARS] + logger.error("Nous /models returned status=%s url=%s body=%s", resp.status_code, url, body) + raise NousAPIError(resp.status_code, _body_text(resp), url) + try: + data = resp.json() + except ValueError as exc: + raise NousAPIError( + resp.status_code, + f"non-JSON /models body: {_body_text(resp)[:BODY_LOG_CHARS]}", + url, + ) from exc + items = data + if isinstance(data, dict): + items = data.get("data") or data.get("models") or [] + ids: list[str] = [] + for item in items or []: + if isinstance(item, dict): + mid = item.get("id") or item.get("name") or item.get("model") + else: + mid = item + if isinstance(mid, str) and mid: + ids.append(mid) + return ids + + +def _near_matches(model: str, ids: list[str], n: int = 3) -> list[str]: + """A couple of ids that look like what the operator probably meant.""" + matches = difflib.get_close_matches(model, ids, n=n, cutoff=0.45) + org, sep, tail = model.partition("/") + stem = tail.split(":", 1)[0].split("-", 1)[0] if sep else "" + extra = [ + mid + for mid in ids + if mid not in matches + and ((sep and mid.split("/", 1)[0] == org) or (stem and stem.lower() in mid.lower())) + ] + return (matches + extra)[:n] + + +def model_available(*, api_key: str, base_url: str | None = None, model: str) -> bool: + """True when ``model`` is offered by the portal; cached once per process. + + Fails open (True, with a warning) when /models itself is unreachable: a + flaky listing endpoint must not disable the pipeline, and ``chat()`` now + raises on a genuinely rejected model id anyway. + """ + resolved = _resolve_base(base_url) + key = (resolved, model) + if key in _MODEL_AVAILABLE: + return _MODEL_AVAILABLE[key] + try: + ids = list_models(api_key=api_key, base_url=resolved) + except (NousAPIError, httpx.HTTPError) as exc: + logger.warning( + "Could not validate SUMMARY_MODEL=%s against %s/models (%s) — " + "continuing without startup validation", + model, resolved, exc, + ) + return True + available = model in ids + if not available: + near = _near_matches(model, ids) + logger.error( + "SUMMARY_MODEL=%r is not offered by %s (%d models listed). " + "Near matches: %s. Runs are skipped until the model exists.", + model, resolved, len(ids), ", ".join(near) if near else "none", + ) + _MODEL_AVAILABLE[key] = available + return available + + +def reset_model_cache() -> None: + """Drop the per-process /models memo (tests, or a long-lived scheduler).""" + _MODEL_AVAILABLE.clear() diff --git a/news/summerizer/run_news_summarizer.py b/news/summerizer/run_news_summarizer.py index dca6d68..3a2082d 100644 --- a/news/summerizer/run_news_summarizer.py +++ b/news/summerizer/run_news_summarizer.py @@ -89,7 +89,13 @@ def run_summarize(*, recap: bool = False) -> None: proc = subprocess.run( [sys.executable, "summarizer.py"], cwd="/app", env=env ) - logger.info("%s finished rc=%s", kind, proc.returncode) + if proc.returncode: + logger.error( + "%s finished rc=%s — run produced no brief (see summarizer log above)", + kind, proc.returncode, + ) + else: + logger.info("%s finished rc=0", kind) except Exception: # noqa: BLE001 — keep the loop alive across failures logger.exception("%s failed", kind) diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index dabf701..c91b3b6 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -21,6 +21,7 @@ of each summarize_news() — env wins, else api_keys / app_settings: SUMMARY_DEDUPE "0" disables syndication dedupe (default on) SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85) BATCH_SIZE articles per map-phase batch (default 50) + SUMMARY_MAP_CONCURRENCY concurrent map calls in flight (default 16) SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set) NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt) NEWS_SUMMARIZE_FORCE "1" to ignore the interval/recap idempotency skip @@ -32,6 +33,9 @@ from __future__ import annotations import logging import os +import sys +import time +from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from zoneinfo import ZoneInfo @@ -51,7 +55,7 @@ from intel import ( select_map, select_ticker, ) -from nous_client import chat +from nous_client import NousAPIError, chat, model_available logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logger = logging.getLogger("news.summarizer") @@ -79,6 +83,14 @@ DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40 DEFAULT_SUMMARY_DEDUPE_SIMILARITY = 0.85 _FALSY = ("0", "false", "no", "off") +# Map-phase fan-out. 745 batches at ~16 s serial is 3.3 h; the nightly recap +# has to finish long before morning, so map calls run concurrently while the +# reduce stays serial (it is one call). Measured on the real 24h backlog +# (2985 articles / 745 batches, deepseek/deepseek-v4.1-flash-1017): each call +# is ~20 s wall, so throughput tracks the concurrency; 16 lands the recap +# under 20 minutes. +DEFAULT_SUMMARY_MAP_CONCURRENCY = 16 + def _env_int(name: str, default: int) -> int: raw = (os.getenv(name) or "").strip() @@ -102,6 +114,11 @@ def _env_float(name: str, default: float) -> float: return default +def map_concurrency() -> int: + """Concurrent map calls in flight (SUMMARY_MAP_CONCURRENCY, default 8).""" + return max(1, _env_int("SUMMARY_MAP_CONCURRENCY", DEFAULT_SUMMARY_MAP_CONCURRENCY)) + + def dedupe_config() -> tuple[bool, float]: """(enabled, similarity) from env. SUMMARY_DEDUPE=0 skips dedupe entirely.""" enabled = (os.getenv("SUMMARY_DEDUPE") or "1").strip().lower() not in _FALSY @@ -693,10 +710,72 @@ def build_master_prompt(final_input: str, recap: bool = False) -> str: return template -def summarize_news() -> None: - """Map-reduce summarize recent articles and store brief + ticker + map.""" +def map_phase( + articles: list[dict], + *, + api_key: str, + model: str, + base_url: str, + concurrency: int | None = None, +) -> tuple[list[tuple[int, str]], int, int]: + """Run the map calls concurrently and return ([(batch_index, response)], empty, total). + + At most ``concurrency`` calls are in flight (a fixed-size thread pool is the + cap, not a suggestion). Responses come back in batch order so grading stays + deterministic. ``NousAPIError`` (400/404/422 — e.g. a retired model id) + aborts the phase: the remaining queued batches are cancelled and the + exception propagates to the caller. + """ + total = -(-len(articles) // BATCH_SIZE) + workers = max(1, concurrency if concurrency is not None else map_concurrency()) + + def run_batch(batch_index: int) -> tuple[int, str]: + batch = articles[batch_index * BATCH_SIZE : (batch_index + 1) * BATCH_SIZE] + return batch_index, call_llm( + build_map_prompt(batch), + api_key=api_key, + model=model, + base_url=base_url, + json_mode=False, + ) + + logger.info("map phase: %d batches (%d articles), concurrency=%d", total, len(articles), workers) + responses: dict[int, str] = {} + empty = 0 + pool = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="news-map") + futures = [pool.submit(run_batch, i) for i in range(total)] + try: + for done, future in enumerate(as_completed(futures), start=1): + batch_index, response = future.result() + if response: + responses[batch_index] = response + else: + empty += 1 + logger.warning("map batch %d/%d returned empty", batch_index + 1, total) + if done % 10 == 0 or done == total: + logger.info( + "map progress %d/%d batches (ok=%d empty=%d)", + done, total, len(responses), empty, + ) + except BaseException: + for future in futures: + future.cancel() + raise + finally: + pool.shutdown(wait=True, cancel_futures=True) + return [(i, responses[i]) for i in sorted(responses)], empty, total + + +def summarize_news() -> int: + """Map-reduce summarize recent articles and store brief + ticker + map. + + Returns a process exit code: 0 on success or an intentional skip, non-zero + when no brief could be produced — the scheduler logs rc != 0, so a dead + model or API never again looks like a quiet, empty success. + """ recap = is_recap_run() window = effective_window_minutes(recap=recap) + started = time.monotonic() ensure_tables() if recap: if _already_recapped_today(): @@ -704,26 +783,34 @@ def summarize_news() -> None: "Skipping recap: article_summaries already has daily_recap today " "(set NEWS_SUMMARIZE_FORCE=1 to override)" ) - return + return 0 elif _already_summarized_this_interval(): logger.info( "Skipping summarize: article_summaries already has a row in the last %ss " "(set NEWS_SUMMARIZE_FORCE=1 to override)", _summarize_interval_seconds(), ) - return + return 0 api_key = resolve_api_key() model = resolve_model() base_url = resolve_base_url() if not api_key: - logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run") - return + logger.error("NOUS_API_KEY unset in env and api_keys — cannot summarize (rc=1)") + return 1 + # One GET /models per process. A retired SUMMARY_MODEL disables the run + # here instead of turning into 745 silent 404s. + if not model_available(api_key=api_key, base_url=base_url, model=model): + logger.error( + "SUMMARY_MODEL=%s is not offered by %s — skipping this run (rc=2)", + model, base_url, + ) + return 2 articles = get_recent_news(window) if not articles: logger.info("No new articles found in the last %s min.", window) - return + return 0 min_score, top_n, fallback_top, fallback_min_score = selection_config() logger.info( @@ -734,22 +821,19 @@ def summarize_news() -> None: ) graded: list[dict] = [] - for i in range(0, len(articles), BATCH_SIZE): - batch = articles[i : i + BATCH_SIZE] - batch_index = i // BATCH_SIZE - logger.info( - "map batch %d/%d (%d articles)", - batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch), + try: + mapped, empty, total_batches = map_phase( + articles, api_key=api_key, model=model, base_url=base_url ) - response = call_llm( - build_map_prompt(batch), - api_key=api_key, - model=model, - base_url=base_url, - json_mode=False, + except NousAPIError as exc: + logger.error( + "map phase aborted on a non-retryable Nous API error (%s) — run failed (rc=1)", + exc, ) - if not response: - continue + return 1 + + for batch_index, response in mapped: + batch = articles[batch_index * BATCH_SIZE : (batch_index + 1) * BATCH_SIZE] blocks, stats = parse_map_scores( response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE ) @@ -766,8 +850,12 @@ def summarize_news() -> None: graded.extend(blocks) if not graded: - logger.warning("No article blocks parsed from the map phase — nothing to reduce.") - return + logger.error( + "map phase produced no article blocks (%d/%d batches empty) — " + "nothing to reduce, run failed (rc=1)", + empty, total_batches, + ) + return 1 dedupe_enabled, dedupe_similarity = dedupe_config() distinct, dedupe_stats = dedupe_blocks( @@ -826,8 +914,8 @@ def summarize_news() -> None: json_mode=True, ) if not master_raw: - logger.warning("Reduce phase returned empty — nothing to persist.") - return + logger.error("Reduce phase returned empty — nothing to persist, run failed (rc=1)") + return 1 parsed = parse_reduce_json(master_raw) selected_articles = [ block["article"] @@ -843,7 +931,22 @@ def summarize_news() -> None: articles=selected_articles, ) persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model) + elapsed = time.monotonic() - started + if not summary_id: + logger.error( + "summarize failed: brief was not persisted (kind=%s, %.1fs) (rc=1)", + "daily_recap" if recap else "interval", elapsed, + ) + return 1 + logger.info( + "summarize done kind=%s summary_id=%s model=%s batches=%d/%d articles=%d " + "ticker=%d map=%d elapsed=%.1fs", + "daily_recap" if recap else "interval", summary_id, model, + len(mapped), total_batches, len(articles), + len(parsed["ticker"]), len(parsed["map_items"]), elapsed, + ) + return 0 if __name__ == "__main__": - summarize_news() + sys.exit(summarize_news()) diff --git a/news/summerizer/tests/conftest.py b/news/summerizer/tests/conftest.py index 8cb64cd..e8effe2 100644 --- a/news/summerizer/tests/conftest.py +++ b/news/summerizer/tests/conftest.py @@ -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() diff --git a/news/summerizer/tests/test_map_concurrency.py b/news/summerizer/tests/test_map_concurrency.py new file mode 100644 index 0000000..2a42b47 --- /dev/null +++ b/news/summerizer/tests/test_map_concurrency.py @@ -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 diff --git a/news/summerizer/tests/test_nous_client.py b/news/summerizer/tests/test_nous_client.py index 848db14..bfd8107 100644 --- a/news/summerizer/tests/test_nous_client.py +++ b/news/summerizer/tests/test_nous_client.py @@ -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)