"""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