Merge pull request 'feat(summarizer): score articles in the map phase, brief only the important ones' (#53) from wt/t_87992985 into master
Some checks failed
build-and-deploy / build-push-deploy (push) Failing after 8s

This commit is contained in:
sirius 2026-11-14 02:49:24 +00:00
commit 2c41737d42
8 changed files with 775 additions and 37 deletions

View file

@ -1,4 +1,4 @@
"""Pure parser for the news-summarizer reduce JSON / geo / importance contract."""
"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
from __future__ import annotations
@ -16,6 +16,16 @@ MAP_HEADLINE_MAX = 160
TICKER_CAP = 12
MAP_CAP = 20
# ── Map-phase grading (score parsing + selection, pure) ────────────────────
# Importance label → stand-in score, used when the map model omits Score:.
IMPORTANCE_SCORE = {"critical": 95, "high": 78, "medium": 50, "low": 22, "none": 5}
NEUTRAL_SCORE = 50
_ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNORECASE | re.MULTILINE)
_SCORE_RE = re.compile(r"Score:\s*(\d{1,3})", re.IGNORECASE)
_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE)
_CATEGORY_RE = re.compile(r"Category:\s*(.+)", re.IGNORECASE)
def parse_reduce_json(raw: str) -> dict:
try:
@ -102,3 +112,123 @@ def select_map(items: list) -> list:
if len(out) >= MAP_CAP:
break
return out
# ── Map grading ────────────────────────────────────────────────────────────
def _clamp_score(value: int) -> int:
return max(0, min(100, int(value)))
def _score_from_block(text: str) -> tuple[int, bool]:
"""Score for one article block. Second element True when a fallback was used."""
match = _SCORE_RE.search(text)
if match:
try:
return _clamp_score(int(match.group(1))), False
except (TypeError, ValueError):
pass
match = _IMPORTANCE_RE.search(text)
if match:
return IMPORTANCE_SCORE.get(match.group(1).lower(), NEUTRAL_SCORE), True
return NEUTRAL_SCORE, True
def _category_from_block(text: str) -> str | None:
match = _CATEGORY_RE.search(text)
if not match:
return None
value = match.group(1).strip().strip("*_` ").rstrip(".").strip()
return value[:40] or None
def parse_map_scores(
raw: str, *, articles: list[dict], batch_index: int = 0, batch_size: int = 1
) -> tuple[list[dict], dict]:
"""Split one map response into scored per-article blocks.
Pure: no DB, no logging. Block ``n`` of batch ``b`` is attributed to
``articles[b * batch_size + n - 1]``. Blocks whose ``Article <n>`` number does
not land inside this batch (model omitted/reordered articles) are counted in
``stats["unattributed"]`` and dropped — there is no article row to attribute
them to. Never raises.
Returns ``(blocks, stats)`` where each block is::
{"n", "article", "article_id", "score", "importance", "category",
"text", "position"}
"""
text = raw or ""
matches = list(_ARTICLE_RE.finditer(text))
blocks: list[dict] = []
seen: set[int] = set()
fallback = 0
unattributed = 0
size = max(1, int(batch_size))
for pos, match in enumerate(matches):
try:
n = int(match.group(1))
except (TypeError, ValueError):
unattributed += 1
continue
if n in seen:
unattributed += 1
continue
seen.add(n)
end = matches[pos + 1].start() if pos + 1 < len(matches) else len(text)
block_text = text[match.start():end].strip()
offset = int(batch_index) * size + n - 1
article = articles[offset] if 0 <= offset < len(articles) else None
if article is None or not block_text:
unattributed += 1
continue
score, used_fallback = _score_from_block(block_text)
fallback += 1 if used_fallback else 0
importance = None
imp_match = _IMPORTANCE_RE.search(block_text)
if imp_match:
importance = imp_match.group(1).lower()
blocks.append(
{
"n": n,
"article": article,
"article_id": article.get("id"),
"score": score,
"importance": importance,
"category": _category_from_block(block_text),
"text": block_text,
"position": offset,
}
)
stats = {
"blocks": len(matches),
"graded": len(blocks),
"fallback": fallback,
"unattributed": unattributed,
}
return blocks, stats
def select_graded(
blocks: list[dict], *, min_score: int, top_n: int, fallback_top: int
) -> tuple[list[dict], bool]:
"""Rank blocks best-first and return the ones the reduce phase should see.
Keeps ``score >= min_score`` capped at ``top_n`` (stable on ties: original
order). When nothing clears the bar, returns the top ``fallback_top`` blocks
and True; ``fallback_top == 0`` yields an empty selection.
"""
ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0))
limit = max(0, int(top_n))
clearing = [b for b in ordered if int(b.get("score") or 0) >= int(min_score)]
if clearing:
return clearing[:limit], False
fallback_limit = max(0, int(fallback_top))
if fallback_limit <= 0:
return [], False
return ordered[:fallback_limit], bool(ordered)
def join_blocks(blocks: list[dict]) -> str:
"""Reduce-phase DATA text: only these blocks, original text, best-first."""
return "\n\n".join(b["text"] for b in blocks)

View file

@ -31,7 +31,7 @@ from zoneinfo import ZoneInfo
import psycopg2
from intel import parse_reduce_json, select_map, select_ticker
from intel import join_blocks, parse_map_scores, parse_reduce_json, select_graded, select_map, select_ticker
from nous_client import chat
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
@ -50,6 +50,30 @@ DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
# Map-phase grading knobs (operator sets them in the cluster ConfigMap).
DEFAULT_SUMMARY_MIN_SCORE = 60
DEFAULT_SUMMARY_TOP_N = 12
DEFAULT_SUMMARY_FALLBACK_TOP = 3
def _env_int(name: str, default: int) -> int:
raw = (os.getenv(name) or "").strip()
if not raw:
return default
try:
return int(raw)
except ValueError:
logger.warning("Invalid %s=%r — using default %s", name, raw, default)
return default
def selection_config() -> tuple[int, int, int]:
"""(min_score, top_n, fallback_top) from env, read per run."""
min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE)))
top_n = max(0, _env_int("SUMMARY_TOP_N", DEFAULT_SUMMARY_TOP_N))
fallback_top = max(0, _env_int("SUMMARY_FALLBACK_TOP", DEFAULT_SUMMARY_FALLBACK_TOP))
return min_score, top_n, fallback_top
def _summary_window_minutes() -> int:
hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip()
@ -94,30 +118,40 @@ FUTURES_TICKERS = {
MAP_PROMPT_DEFAULT = """\
You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts.
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. If the batch has no critical/high stories, still extract minor incidents and crime reports.
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. Extract every article; the Score below decides what reaches the operator brief.
Write every field in English. Translate if the article is not English.
Grade every article with this rubric before writing anything else in its block:
- 90–100 — breaking geopolitical/military/security event or major disaster, immediate consequence
- 70–89 — significant national/international politics, conflict, security, infrastructure or disaster news
- 40–69 — notable regional/economic/tech/health story with real consequences
- 10–39 — routine, minor or single-incident crime; local interest
- 0–9 — noise: sport, celebrity, entertainment, market/commodity tape, promotional or event-calendar/schedule listings
For EACH article in the batch:
1. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
5. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
6. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none.
1. Score: the integer 0-100 from the rubric above, first line of the block.
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score.
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
Output format — strictly one block per article:
Output format — strictly one block per article, Score and Importance first:
Article 1:
- Score: <0-100>
- Importance: critical|high|medium|low|none
- Fact bullet 1
- Fact bullet 2
- Location: ...
- Entities: ...
- Category: ...
- OSINT signal: ...
- Importance: ...
- Lat: ...
- Lon: ...
@ -133,9 +167,11 @@ You are writing an English operator HUD brief from the article facts in DATA bel
Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the brief with minor incidents and crime reports rather than writing an empty or unfinished brief. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
ticker: only stories present in DATA, highest score first.
map_items may be empty if no located critical/high event is explicit in the data.
@ -160,9 +196,11 @@ You are writing a daily recap of the last 24 hours of news for an OSINT operator
Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the recap with minor incidents and crime reports rather than writing an empty or unfinished recap. Never truncate mid-sentence; finish every sentence.
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories of the day and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence.
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
ticker: only stories present in DATA, highest score first.
Demand a single JSON object (no markdown fences) with this exact shape:
@ -326,6 +364,18 @@ def ensure_tables() -> None:
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
ON news_items (lon, lat)
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL;
CREATE TABLE IF NOT EXISTS article_scores (
article_id INTEGER NOT NULL,
summary_id INTEGER,
score INTEGER NOT NULL,
category TEXT,
selected BOOLEAN NOT NULL,
model TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (article_id, created_at)
);
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
ON article_scores (summary_id);
"""
try:
conn = psycopg2.connect(**DB_CONFIG)
@ -342,7 +392,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]:
"""Fetch articles from the look-back window (content > 100 chars)."""
mins = window_minutes if window_minutes is not None else effective_window_minutes()
query = """
SELECT title, content, url, domain
SELECT id, title, content, url, domain
FROM articles
WHERE timestamp > NOW() - make_interval(mins => %s)
AND content IS NOT NULL AND length(content) > 100
@ -356,7 +406,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]:
cur.close()
conn.close()
return [
{"title": r[0], "content": r[1], "url": r[2], "domain": r[3]}
{"id": r[0], "title": r[1], "content": r[2], "url": r[3], "domain": r[4]}
for r in rows
]
except Exception as exc: # noqa: BLE001
@ -412,14 +462,14 @@ def _already_recapped_today() -> bool:
def save_batch(
summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval"
) -> None:
"""Insert the master brief plus flagged ticker/map rows."""
) -> int | None:
"""Insert the master brief plus flagged ticker/map rows. Returns the new summary id."""
ticker_rows = select_ticker(ticker or [])
map_rows = select_map(map_items or [])
text = (summary_en or "").strip()
if len(text) < 10 and not ticker_rows and not map_rows:
logger.info("Summary too short or empty. Skipping save.")
return
return None
insert_item = """
INSERT INTO news_items (
summary_id, kind, headline, importance, location_name,
@ -473,8 +523,54 @@ def save_batch(
)
cur.close()
conn.close()
return summary_id
except Exception as exc: # noqa: BLE001
logger.error("Error saving batch to DB: %s", exc)
return None
def persist_article_scores(
graded: list[dict], *, summary_id: int | None, model: str
) -> None:
"""Insert one article_scores row per graded article (selected true/false).
Best-effort: a failure here is logged and never aborts the run.
"""
rows = []
for block in graded or []:
article_id = block.get("article_id")
if article_id is None:
continue
rows.append(
(
article_id,
summary_id,
int(block.get("score") or 0),
block.get("category"),
bool(block.get("selected")),
model,
)
)
if not rows:
return
try:
conn = psycopg2.connect(**DB_CONFIG)
cur = conn.cursor()
cur.executemany(
"INSERT INTO article_scores "
"(article_id, summary_id, score, category, selected, model) "
"VALUES (%s, %s, %s, %s, %s, %s)",
rows,
)
conn.commit()
cur.close()
conn.close()
logger.info(
"article_scores persisted rows=%d selected=%d summary_id=%s",
len(rows), sum(1 for r in rows if r[4]), summary_id,
)
except Exception as exc: # noqa: BLE001
logger.error("Error persisting article_scores (run continues): %s", exc)
# ── Orchestration ──────────────────────────────────────────────────────────
@ -533,34 +629,69 @@ def summarize_news() -> None:
logger.info("No new articles found in the last %s min.", window)
return
min_score, top_n, fallback_top = selection_config()
logger.info(
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s)...",
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, "
"min_score=%d, top_n=%d, fallback_top=%d)...",
len(articles), model, BATCH_SIZE, recap, window,
min_score, top_n, fallback_top,
)
partial_summaries: list[str] = []
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)",
i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch),
batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch),
)
summary = call_llm(
response = call_llm(
build_map_prompt(batch),
api_key=api_key,
model=model,
base_url=base_url,
json_mode=False,
)
if summary:
partial_summaries.append(summary)
if not response:
continue
blocks, stats = parse_map_scores(
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
)
logger.info(
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d)",
batch_index + 1, stats["graded"], len(batch),
stats["fallback"], stats["unattributed"],
)
graded.extend(blocks)
final_input = "\n\n".join(partial_summaries)
if not final_input.strip():
logger.warning("No partial summaries produced — nothing to reduce.")
if not graded:
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
return
logger.info("reduce phase over %d partial summaries", len(partial_summaries))
selected, used_fallback = select_graded(
graded, min_score=min_score, top_n=top_n, fallback_top=fallback_top
)
selected_positions = {block["position"] for block in selected}
for block in graded:
block["selected"] = block["position"] in selected_positions
if used_fallback:
logger.warning(
"No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d "
"(max score %d)",
min_score, len(selected), max(b["score"] for b in graded),
)
logger.info(
"selected %d/%d graded articles for reduce (scores=%s)",
len(selected), len(graded), [b["score"] for b in selected],
)
final_input = join_blocks(selected)
if not final_input.strip():
logger.warning(
"Selection is empty (min_score=%d, fallback_top=%d) — reduce gets empty DATA.",
min_score, fallback_top,
)
master_raw = call_llm(
build_master_prompt(final_input, recap=recap),
api_key=api_key,
@ -572,13 +703,14 @@ def summarize_news() -> None:
logger.warning("Reduce phase returned empty — nothing to persist.")
return
parsed = parse_reduce_json(master_raw)
save_batch(
summary_id = save_batch(
parsed["summary_en"],
model,
parsed["ticker"],
parsed["map_items"],
kind="daily_recap" if recap else "interval",
)
persist_article_scores(graded, summary_id=summary_id, model=model)
if __name__ == "__main__":

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():