Two leaks let low-value items reach the operator brief: - get_recent_news() only bounded the window from below, so event listings dated days ahead (wiseye.org, +3d/+6d) were re-fetched, re-graded and re-billed every interval for a week. The window is now (now - N, now]; NULL timestamps stay excluded as before. - select_graded() returned ordered[:fallback_top] with no floor, so a 15/100 event listing entered the brief as 'low'. New SUMMARY_FALLBACK_MIN_SCORE (default 40, clamped 0-100) filters the fallback set; when nothing clears it the reduce phase gets empty DATA and writes the empty-brief response. The fallback WARNING now logs the floor. Docs: .env.example and docs/news.md document the new knob and window.
231 lines
7.8 KiB
Python
231 lines
7.8 KiB
Python
"""Offline end-to-end: map grading feeds a thresholded subset to the reduce phase."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
import summarizer
|
|
|
|
|
|
class _FakeCursor:
|
|
def __init__(self, log: list):
|
|
self.log = log
|
|
self._sql = ""
|
|
|
|
def execute(self, sql, params=None):
|
|
self._sql = " ".join(sql.split())
|
|
self.log.append(("execute", self._sql, params))
|
|
|
|
def executemany(self, sql, rows):
|
|
self.log.append(("executemany", " ".join(sql.split()), list(rows)))
|
|
|
|
def fetchone(self):
|
|
if "article_summaries" in self._sql:
|
|
return (42,)
|
|
return None
|
|
|
|
def fetchall(self):
|
|
return []
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
|
|
class _FakeConn:
|
|
def __init__(self, log: list):
|
|
self.log = log
|
|
|
|
def cursor(self):
|
|
return _FakeCursor(self.log)
|
|
|
|
def commit(self):
|
|
self.log.append(("commit",))
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
|
|
def _articles(n: int = 6) -> list[dict]:
|
|
return [
|
|
{
|
|
"id": i + 1,
|
|
"title": f"Story {i + 1}",
|
|
"content": f"Body of story {i + 1} " + "x" * 120,
|
|
"url": f"https://ex.com/{i + 1}",
|
|
"domain": "ex.com",
|
|
}
|
|
for i in range(n)
|
|
]
|
|
|
|
|
|
def _block(n: int, score=None, importance=None) -> str:
|
|
lines = [f"Article {n}:", "- Fact bullet one"]
|
|
if score is not None:
|
|
lines.append(f"- Score: {score}")
|
|
if importance is not None:
|
|
lines.append(f"- Importance: {importance}")
|
|
lines += ["- Location: Kyiv", "- Entities: None", "- Category: politics",
|
|
"- OSINT signal: No notable OSINT signal.", "- Lat: 50.45", "- Lon: 30.52"]
|
|
return "\n".join(lines)
|
|
|
|
|
|
MAP_REPLIES = [
|
|
# batch 0 → articles 1..3
|
|
"\n\n".join([_block(1, score=92), _block(2, score=34), _block(3, score=81)]),
|
|
# batch 1 → articles 4..6 (numbering restarts; article 6 loses its Score line)
|
|
"\n\n".join([_block(1, score=12), _block(2, score=66), _block(3, importance="low")]),
|
|
]
|
|
|
|
REDUCE_REPLY = json.dumps(
|
|
{
|
|
"summary_en": "Lead: strike in Kyiv. Also: minister resigns.",
|
|
"ticker": [
|
|
{"headline": "Strike in Kyiv", "importance": "critical", "url": "https://ex.com/1"},
|
|
],
|
|
"map_items": [
|
|
{
|
|
"headline": "Strike in Kyiv",
|
|
"importance": "critical",
|
|
"location_name": "Kyiv",
|
|
"lat": 50.45,
|
|
"lon": 30.52,
|
|
"location_confidence": "city",
|
|
"category": "military/conflict",
|
|
"url": "https://ex.com/1",
|
|
}
|
|
],
|
|
}
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def harness(monkeypatch):
|
|
"""Run summarize_news offline: fake DB, fake LLM, 6 articles, BATCH_SIZE=3."""
|
|
calls: list[tuple[str, str]] = []
|
|
db_log: list = []
|
|
|
|
def fake_call_llm(prompt, *, api_key, model, base_url, json_mode=False):
|
|
calls.append(("json" if json_mode else "text", prompt))
|
|
return REDUCE_REPLY if json_mode else MAP_REPLIES[len(calls) - 1]
|
|
|
|
monkeypatch.setenv("NOUS_API_KEY", "test-key")
|
|
monkeypatch.setenv("SUMMARY_MODEL", "test-model")
|
|
monkeypatch.setattr(summarizer, "BATCH_SIZE", 3)
|
|
monkeypatch.setattr(summarizer, "call_llm", fake_call_llm)
|
|
monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: _articles())
|
|
monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False)
|
|
monkeypatch.setattr(summarizer, "_already_recapped_today", lambda: False)
|
|
monkeypatch.setattr(
|
|
summarizer.psycopg2, "connect", lambda **kwargs: _FakeConn(db_log)
|
|
)
|
|
return calls, db_log
|
|
|
|
|
|
def _score_rows(db_log: list) -> list[tuple]:
|
|
rows = [entry[2] for entry in db_log if entry[0] == "executemany"]
|
|
assert rows, f"no executemany in db log: {db_log}"
|
|
return rows[-1]
|
|
|
|
|
|
def test_reduce_sees_only_articles_above_the_threshold(harness):
|
|
calls, db_log = harness
|
|
summarizer.summarize_news()
|
|
|
|
reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0]
|
|
# Selected: 92 (article 1), 81 (article 3), 66 (article 5) — best first.
|
|
assert reduce_prompt.index("Score: 92") < reduce_prompt.index("Score: 81")
|
|
assert reduce_prompt.index("Score: 81") < reduce_prompt.index("Score: 66")
|
|
for leaked in ("Score: 34", "Score: 12", "Importance: low"):
|
|
assert leaked not in reduce_prompt
|
|
|
|
rows = _score_rows(db_log)
|
|
assert len(rows) == 6
|
|
by_article = {row[0]: row for row in rows}
|
|
assert by_article[6][2] == 22 # Importance: low fallback
|
|
assert sorted(aid for aid, row in by_article.items() if row[4]) == [1, 3, 5]
|
|
assert {row[1] for row in rows} == {42} # summary_id from save_batch
|
|
assert {row[5] for row in rows} == {"test-model"}
|
|
assert by_article[1][3] == "politics"
|
|
|
|
|
|
def test_all_low_scores_fall_back_to_top_three(harness, monkeypatch):
|
|
calls, db_log = harness
|
|
monkeypatch.setenv("SUMMARY_MIN_SCORE", "95")
|
|
monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "3")
|
|
summarizer.summarize_news()
|
|
|
|
reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0]
|
|
# Top three by score: 92 (article 1), 81 (article 3), 66 (article 5).
|
|
for kept in ("Score: 92", "Score: 81", "Score: 66"):
|
|
assert kept in reduce_prompt
|
|
for dropped in ("Score: 34", "Score: 12", "Importance: low"):
|
|
assert dropped not in reduce_prompt
|
|
assert sorted(row[0] for row in _score_rows(db_log) if row[4]) == [1, 3, 5]
|
|
|
|
|
|
def test_fallback_top_zero_sends_empty_data(harness, monkeypatch):
|
|
calls, db_log = harness
|
|
monkeypatch.setenv("SUMMARY_MIN_SCORE", "95")
|
|
monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "0")
|
|
summarizer.summarize_news()
|
|
|
|
reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0]
|
|
assert "Score: 92" not in reduce_prompt
|
|
assert reduce_prompt.rstrip().endswith("DATA:")
|
|
assert not any(row[4] for row in _score_rows(db_log))
|
|
|
|
|
|
def test_fallback_below_the_floor_sends_empty_data(harness, monkeypatch, caplog):
|
|
"""Every block scores under the floor (max 92 < 93): no fallback at all."""
|
|
calls, db_log = harness
|
|
monkeypatch.setenv("SUMMARY_MIN_SCORE", "95")
|
|
monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "93")
|
|
with caplog.at_level("WARNING"):
|
|
summarizer.summarize_news()
|
|
|
|
reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0]
|
|
assert "Score: 92" not in reduce_prompt
|
|
assert reduce_prompt.rstrip().endswith("DATA:")
|
|
assert not any(row[4] for row in _score_rows(db_log))
|
|
assert any("fallback_min_score=93" in rec.message for rec in caplog.records)
|
|
|
|
|
|
def test_fallback_floor_is_logged_in_the_warning(harness, monkeypatch, caplog):
|
|
calls, _ = harness
|
|
monkeypatch.setenv("SUMMARY_MIN_SCORE", "95")
|
|
monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "3")
|
|
monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "40")
|
|
with caplog.at_level("WARNING"):
|
|
summarizer.summarize_news()
|
|
|
|
warnings = [rec.message for rec in caplog.records if rec.levelname == "WARNING"]
|
|
assert any(
|
|
"fallback to top 3 with score >= 40 (max score 92)" in msg for msg in warnings
|
|
), warnings
|
|
|
|
|
|
def test_score_insert_failure_does_not_abort_the_run(harness, monkeypatch):
|
|
calls, db_log = harness
|
|
|
|
class _BoomConn(_FakeConn):
|
|
def cursor(self):
|
|
raise RuntimeError("article_scores unavailable")
|
|
|
|
real_connect = summarizer.psycopg2.connect
|
|
state = {"n": 0}
|
|
|
|
def flaky_connect(**kwargs):
|
|
# First connect = ensure_tables, second = save_batch, third = scores.
|
|
state["n"] += 1
|
|
if state["n"] >= 3:
|
|
return _BoomConn(db_log)
|
|
return real_connect(**kwargs)
|
|
|
|
monkeypatch.setattr(summarizer.psycopg2, "connect", flaky_connect)
|
|
summarizer.summarize_news() # must not raise
|
|
|
|
kinds = [kind for kind, _ in calls]
|
|
assert kinds.count("json") == 1 # reduce still ran
|
|
assert any(entry[0] == "execute" and "article_summaries" in entry[1] for entry in db_log)
|