feat(summarizer): score articles in the map phase, brief only the important ones

The map prompt now grades every article 0-100 against an explicit rubric as
the first line of its block; the summarizer parses Score:, falls back to the
Importance: label when the line is missing, ranks blocks best-first and passes
only score >= SUMMARY_MIN_SCORE (capped at SUMMARY_TOP_N) to the reduce phase.

- new pure helpers in intel.py: parse_map_scores(), select_graded(), join_blocks()
- reduce prompts drop the 'fill the brief with minor incidents and crime'
  filler instructions and the 'fill ticker with medium then low' clause
- new article_scores table (ensure_tables + alembic 012) persists every grade
  with selected/summary_id/model so thresholds can be tuned from data
- SUMMARY_MIN_SCORE (60), SUMMARY_TOP_N (12), SUMMARY_FALLBACK_TOP (3) env knobs
This commit is contained in:
hermes-backend 2026-11-13 21:47:30 -05:00
commit 853e87b7c5
8 changed files with 775 additions and 37 deletions

View file

@ -0,0 +1,174 @@
"""Map-phase grading: score parsing, batch attribution, selection, reduce input."""
from __future__ import annotations
import pytest
from intel import join_blocks, parse_map_scores, select_graded
def _articles(n: int, start: int = 100) -> list[dict]:
return [
{
"id": start + i,
"title": f"title {i}",
"content": "body",
"url": f"https://ex.com/{i}",
"domain": "ex.com",
}
for i in range(n)
]
def _block(n: int, score=None, importance=None, marker="Article") -> str:
lines = [f"{marker} {n}:"]
if score is not None:
lines.append(f"- Score: {score}")
if importance is not None:
lines.append(f"- Importance: {importance}")
lines.append("- Some fact bullet")
lines.append("- Category: politics")
return "\n".join(lines)
def test_parses_score_line():
raw = _block(1, score=84)
blocks, stats = parse_map_scores(raw, articles=_articles(1))
assert len(blocks) == 1
assert blocks[0]["score"] == 84
assert blocks[0]["importance"] is None
assert stats == {"blocks": 1, "graded": 1, "fallback": 0, "unattributed": 0}
def test_parses_category_and_article_id():
blocks, _ = parse_map_scores(_block(1, score=70), articles=_articles(1))
assert blocks[0]["category"] == "politics"
assert blocks[0]["article_id"] == 100
assert "Score: 70" in blocks[0]["text"]
@pytest.mark.parametrize(
"importance,expected",
[("critical", 95), ("high", 78), ("medium", 50), ("low", 22), ("none", 5)],
)
def test_missing_score_falls_back_to_importance_label(importance, expected):
blocks, stats = parse_map_scores(
_block(1, importance=importance), articles=_articles(1)
)
assert blocks[0]["score"] == expected
assert stats["fallback"] == 1
def test_missing_score_and_missing_importance_defaults_to_50():
blocks, stats = parse_map_scores("Article 1:\n- Some fact bullet", articles=_articles(1))
assert blocks[0]["score"] == 50
assert stats["fallback"] == 1
@pytest.mark.parametrize("line", ["- Score: high", "- Score: n/a", "- Score:"])
def test_garbage_score_line_falls_back(line):
blocks, stats = parse_map_scores(
f"{_block(1, importance='high').replace('- Importance: high', line + chr(10) + '- Importance: high')}",
articles=_articles(1),
)
assert blocks[0]["score"] == 78
assert stats["fallback"] == 1
def test_score_is_clamped():
blocks, stats = parse_map_scores(_block(1, score=150), articles=_articles(1))
assert blocks[0]["score"] == 100
assert stats["fallback"] == 0
blocks, _ = parse_map_scores(_block(1, score=0), articles=_articles(1))
assert blocks[0]["score"] == 0
def test_split_is_case_insensitive_and_markdown_tolerant():
raw = "**article 1:**\n- score: 77\n- Importance: high\n\n ARTICLE 2:\n- Score: 12"
blocks, stats = parse_map_scores(raw, articles=_articles(2))
assert [b["score"] for b in blocks] == [77, 12]
assert stats["graded"] == 2
def test_batch_index_attribution():
articles = _articles(8)
raw = _block(1, score=90) + "\n\n" + _block(2, score=10)
blocks, _ = parse_map_scores(raw, articles=articles, batch_index=1, batch_size=4)
assert [b["article_id"] for b in blocks] == [104, 105]
assert [b["position"] for b in blocks] == [4, 5]
def test_omitted_and_reordered_articles_attribute_by_number():
articles = _articles(4)
raw = "\n\n".join([_block(3, score=30), _block(1, score=88), _block(4, score=61)])
blocks, stats = parse_map_scores(raw, articles=articles, batch_size=4)
assert [b["article_id"] for b in blocks] == [102, 100, 103]
assert stats["graded"] == 3
assert stats["blocks"] == 3
def test_out_of_range_and_duplicate_blocks_are_counted_not_raised():
articles = _articles(2)
raw = "\n\n".join([_block(1, score=90), _block(1, score=20), _block(9, score=80)])
blocks, stats = parse_map_scores(raw, articles=articles, batch_size=2)
assert [b["article_id"] for b in blocks] == [100]
assert stats["unattributed"] == 2
assert stats["blocks"] == 3
@pytest.mark.parametrize("raw", ["", "no article blocks at all", None])
def test_never_raises_on_junk(raw):
blocks, stats = parse_map_scores(raw, articles=_articles(3))
assert blocks == []
assert stats["graded"] == 0
# ── selection ─────────────────────────────────────────────────────────────
def _scored(pairs):
return [
{"position": i, "score": score, "text": f"block {i}"} for i, score in enumerate(pairs)
]
def test_threshold_and_cap_selection_best_first():
blocks = _scored([55, 90, 61, 88, 40, 70])
selected, fallback = select_graded(blocks, min_score=60, top_n=3, fallback_top=3)
assert [b["score"] for b in selected] == [90, 88, 70]
assert [b["text"] for b in selected] == ["block 1", "block 3", "block 5"]
assert fallback is False
def test_ties_keep_original_order():
blocks = _scored([70, 90, 70, 90])
selected, _ = select_graded(blocks, min_score=60, top_n=4, fallback_top=3)
assert [b["text"] for b in selected] == ["block 1", "block 3", "block 0", "block 2"]
def test_nothing_clears_the_bar_uses_fallback_top():
blocks = _scored([40, 12, 55, 3])
selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=3)
assert [b["score"] for b in selected] == [55, 40, 12]
assert fallback is True
def test_fallback_top_zero_yields_empty_selection():
blocks = _scored([40, 12, 55])
selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=0)
assert selected == []
assert fallback is False
assert join_blocks(selected) == ""
def test_empty_blocks_select_nothing():
assert select_graded([], min_score=60, top_n=12, fallback_top=3) == ([], False)
def test_reduce_input_contains_only_selected_blocks():
raw = "\n\n".join([_block(n, score=s) for n, s in [(1, 12), (2, 95), (3, 5)]])
blocks, _ = parse_map_scores(raw, articles=_articles(3), batch_size=3)
selected, _ = select_graded(blocks, min_score=60, top_n=12, fallback_top=3)
data = join_blocks(selected)
assert "Article 2:" in data
assert "Article 1:" not in data
assert "Article 3:" not in data

View file

@ -0,0 +1,202 @@
"""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_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)

View file

@ -22,12 +22,42 @@ def test_summary_prompt_focuses_on_breaking_news_not_futures():
assert "commodity" in p or "market" in p
def test_summary_prompt_covers_critical_then_incidents():
def test_map_prompt_has_the_grading_rubric_and_score_first_block():
p = MAP_PROMPT_DEFAULT
assert "- Score: <0-100>" in p
assert "Importance: critical|high|medium|low|none" in p
for band in (
"90–100",
"70–89",
"40–69",
"10–39",
"0–9",
"event-calendar/schedule listings",
):
assert band in p
# Score must be the first line of the per-article output block.
block = p.split("Article 1:", 1)[1]
first_lines = [line.strip() for line in block.splitlines() if line.strip()]
assert first_lines[0].startswith("- Score:")
def test_reduce_prompts_do_not_demand_filler():
for prompt in (SUMMARY_PROMPT_DEFAULT, RECAP_PROMPT_DEFAULT):
p = prompt.lower()
assert "fill the brief with minor incidents" not in p
assert "fill the recap with minor incidents" not in p
assert "fill ticker with medium then low" not in p
assert "pre-filtered by score" in p
assert "never promote an item above its score" in p
assert "No significant developments in this window." in prompt
def test_summary_prompt_ranks_by_score_and_stays_complete():
p = SUMMARY_PROMPT_DEFAULT.lower()
assert "critical" in p
assert "crime" in p
assert "incident" in p
assert "complete" in p or "truncat" in p or "unfinished" in p or "mid-sentence" in p
assert "highest-scoring" in p
assert "pre-filtered" in p
assert "complete" in p or "truncat" in p or "mid-sentence" in p
def test_summary_prompt_does_not_bail_out_with_canned_empty_brief():