fix(summarizer): ignore future-dated rows; require a score floor for the fallback

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.
This commit is contained in:
backend 2026-11-13 21:56:46 -05:00
commit 57c0444a69
7 changed files with 311 additions and 23 deletions

View file

@ -210,13 +210,20 @@ def parse_map_scores(
def select_graded(
blocks: list[dict], *, min_score: int, top_n: int, fallback_top: int
blocks: list[dict],
*,
min_score: int,
top_n: int,
fallback_top: int,
fallback_min_score: int = 0,
) -> 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.
order). When nothing clears the bar, returns up to ``fallback_top`` blocks
that also clear ``fallback_min_score`` and True; ``fallback_top == 0``, a
floor that excludes every block, or no blocks at all yield an empty
selection and False.
"""
ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0))
limit = max(0, int(top_n))
@ -226,7 +233,11 @@ def select_graded(
fallback_limit = max(0, int(fallback_top))
if fallback_limit <= 0:
return [], False
return ordered[:fallback_limit], bool(ordered)
floor = int(fallback_min_score)
floor_clearing = [b for b in ordered if int(b.get("score") or 0) >= floor]
if not floor_clearing:
return [], False
return floor_clearing[:fallback_limit], True
def join_blocks(blocks: list[dict]) -> str:

View file

@ -54,6 +54,7 @@ BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
DEFAULT_SUMMARY_MIN_SCORE = 60
DEFAULT_SUMMARY_TOP_N = 12
DEFAULT_SUMMARY_FALLBACK_TOP = 3
DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40
def _env_int(name: str, default: int) -> int:
@ -67,12 +68,15 @@ def _env_int(name: str, default: int) -> int:
return default
def selection_config() -> tuple[int, int, int]:
"""(min_score, top_n, fallback_top) from env, read per run."""
def selection_config() -> tuple[int, int, int, int]:
"""(min_score, top_n, fallback_top, fallback_min_score) from env, 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
fallback_min_score = max(
0, min(100, _env_int("SUMMARY_FALLBACK_MIN_SCORE", DEFAULT_SUMMARY_FALLBACK_MIN_SCORE))
)
return min_score, top_n, fallback_top, fallback_min_score
def _summary_window_minutes() -> int:
@ -389,12 +393,18 @@ def ensure_tables() -> None:
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
"""Fetch articles from the look-back window (content > 100 chars)."""
"""Fetch articles from the look-back window ``(now - window, now]``.
The upper bound is deliberate: future-dated rows (event listings, bad
scrape timestamps) must not be re-graded every interval. Rows with a NULL
timestamp have never matched the lower bound and still do not.
"""
mins = window_minutes if window_minutes is not None else effective_window_minutes()
query = """
SELECT id, title, content, url, domain
FROM articles
WHERE timestamp > NOW() - make_interval(mins => %s)
AND timestamp <= NOW()
AND content IS NOT NULL AND length(content) > 100
ORDER BY timestamp DESC;
"""
@ -629,12 +639,12 @@ 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()
min_score, top_n, fallback_top, fallback_min_score = selection_config()
logger.info(
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, "
"min_score=%d, top_n=%d, fallback_top=%d)...",
"min_score=%d, top_n=%d, fallback_top=%d, fallback_min_score=%d)...",
len(articles), model, BATCH_SIZE, recap, window,
min_score, top_n, fallback_top,
min_score, top_n, fallback_top, fallback_min_score,
)
graded: list[dict] = []
@ -669,7 +679,11 @@ def summarize_news() -> None:
return
selected, used_fallback = select_graded(
graded, min_score=min_score, top_n=top_n, fallback_top=fallback_top
graded,
min_score=min_score,
top_n=top_n,
fallback_top=fallback_top,
fallback_min_score=fallback_min_score,
)
selected_positions = {block["position"] for block in selected}
for block in graded:
@ -677,8 +691,9 @@ def summarize_news() -> None:
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),
"with score >= %d (max score %d)",
min_score, len(selected), fallback_min_score,
max(b["score"] for b in graded),
)
logger.info(
"selected %d/%d graded articles for reduce (scores=%s)",
@ -688,8 +703,9 @@ def summarize_news() -> None:
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,
"Selection is empty (min_score=%d, fallback_top=%d, "
"fallback_min_score=%d) — reduce gets empty DATA.",
min_score, fallback_top, fallback_min_score,
)
master_raw = call_llm(

View file

@ -152,6 +152,63 @@ def test_nothing_clears_the_bar_uses_fallback_top():
assert fallback is True
def test_fallback_respects_the_score_floor():
blocks = _scored([45, 30, 15])
selected, fallback = select_graded(
blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=40
)
assert [b["score"] for b in selected] == [45]
assert fallback is True
def test_fallback_floor_drops_everything_below_it():
blocks = _scored([30, 15, 12])
selected, fallback = select_graded(
blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=40
)
assert selected == []
assert fallback is False
assert join_blocks(selected) == ""
def test_fallback_floor_zero_keeps_old_behaviour():
blocks = _scored([40, 12, 55])
selected, fallback = select_graded(
blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=0
)
assert [b["score"] for b in selected] == [55, 40, 12]
assert fallback is True
def test_fallback_floor_does_not_affect_the_threshold_path():
blocks = _scored([95, 45, 30])
selected, fallback = select_graded(
blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=90
)
assert [b["score"] for b in selected] == [95]
assert fallback is False
def test_replay_of_the_observed_run_keeps_only_the_45():
"""Master run #4: scores [45, 30, 15], min_score=60, fallback_top=3."""
blocks = _scored([45, 30, 15])
blocks[0]["text"] = "Article 1:\n- Score: 45\n- Importance: medium\n- Budget fight"
blocks[1]["text"] = "Article 2:\n- Score: 30\n- Importance: low\n- Council meeting"
blocks[2]["text"] = (
"Article 3:\n- Score: 15\n- Importance: low\n"
"- UW-Madison Elections Research Center to host 2026 midterm election symposium"
)
selected, fallback = select_graded(
blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=40
)
assert [b["score"] for b in selected] == [45]
assert fallback is True
data = join_blocks(selected)
assert "Score: 45" in data
assert "symposium" not in data
assert "Council meeting" not in data
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)

View file

@ -177,6 +177,35 @@ def test_fallback_top_zero_sends_empty_data(harness, monkeypatch):
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

View file

@ -1,10 +1,19 @@
"""Summarizer window, recap flag, and no futures injection into prompts."""
"""Summarizer window, recap flag, no futures injection, and grading env knobs."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import pytest
import summarizer
from summarizer import (
build_map_prompt,
build_master_prompt,
effective_window_minutes,
get_recent_news,
is_recap_run,
selection_config,
)
@ -43,3 +52,164 @@ def test_build_master_prompt_recap_uses_daily_template():
assert "partial facts" in prompt
assert "daily recap" in prompt.lower()
assert "24" in prompt
# ── get_recent_news window: (now - window, now] ───────────────────────────
class _WindowCursor:
"""Cursor double that applies the (now-window, now] window to a fixed table.
It emulates PostgreSQL's ``NOW()`` semantics for the window bounds the query
declares, so a query missing the upper bound returns future-dated rows
exactly as the live table did. Rows with a NULL timestamp never satisfy a
range comparison, matching the pre-existing live behaviour.
"""
def __init__(self, rows):
self.rows = rows
self.sql = ""
self.params = None
def execute(self, sql, params=None):
self.sql = " ".join(sql.split())
self.params = params
def fetchall(self):
mins = self.params[0]
now = datetime.now(timezone.utc)
start = now - timedelta(minutes=mins)
has_upper = "timestamp <= NOW()" in self.sql
out = []
for row in self.rows:
ts = row[5]
if ts is None or ts <= start:
continue
if has_upper and ts > now:
continue
out.append(row)
return out
def close(self):
pass
class _WindowConn:
def __init__(self, rows):
self.rows = rows
def cursor(self):
return _WindowCursor(self.rows)
def close(self):
pass
def _row(row_id: int, ts, domain: str = "ex.com") -> tuple:
return (row_id, "title", "x" * 120, f"https://ex.com/{row_id}", domain, ts)
def _patch_articles(monkeypatch, rows):
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _WindowConn(rows))
def test_recent_news_excludes_future_dated_rows(monkeypatch):
now = datetime.now(timezone.utc)
rows = [
_row(1, now - timedelta(minutes=2), "fresh.example"),
_row(2, now + timedelta(days=3), "wiseye.org"),
_row(3, now + timedelta(days=6), "wiseye.org"),
]
_patch_articles(monkeypatch, rows)
news = get_recent_news(15)
assert [n["id"] for n in news] == [1]
assert {n["domain"] for n in news} == {"fresh.example"}
def test_recent_news_window_is_closed_at_now_and_open_at_the_start(monkeypatch):
now = datetime.now(timezone.utc)
rows = [
_row(1, now), # exactly now → inside (now - window, now]
_row(2, now - timedelta(minutes=20)), # older than the 15 min window
]
_patch_articles(monkeypatch, rows)
assert [n["id"] for n in get_recent_news(15)] == [1]
def test_recent_news_still_excludes_null_timestamps(monkeypatch):
now = datetime.now(timezone.utc)
_patch_articles(monkeypatch, [_row(1, None), _row(2, now - timedelta(minutes=1))])
assert [n["id"] for n in get_recent_news(15)] == [2]
def test_recent_news_query_keeps_content_filter_and_ordering(monkeypatch):
captured = {}
class _CaptureCursor(_WindowCursor):
def execute(self, sql, params=None):
super().execute(sql, params)
captured["sql"] = self.sql
class _CaptureConn(_WindowConn):
def cursor(self):
return _CaptureCursor([])
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _CaptureConn([]))
get_recent_news(15)
sql = captured["sql"]
assert "timestamp > NOW() - make_interval(mins => %s)" in sql
assert "timestamp <= NOW()" in sql
assert "content IS NOT NULL AND length(content) > 100" in sql
assert "ORDER BY timestamp DESC" in sql
assert "IS NULL OR" not in sql
assert "COALESCE(timestamp" not in sql
# ── selection_config: SUMMARY_FALLBACK_MIN_SCORE ──────────────────────────
def _clear_selection_env(monkeypatch):
for name in (
"SUMMARY_MIN_SCORE",
"SUMMARY_TOP_N",
"SUMMARY_FALLBACK_TOP",
"SUMMARY_FALLBACK_MIN_SCORE",
):
monkeypatch.delenv(name, raising=False)
def test_selection_config_defaults(monkeypatch):
_clear_selection_env(monkeypatch)
assert selection_config() == (60, 12, 3, 40)
def test_selection_config_reads_the_floor(monkeypatch):
_clear_selection_env(monkeypatch)
monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "55")
assert selection_config()[3] == 55
def test_selection_config_floor_zero_is_honoured(monkeypatch):
_clear_selection_env(monkeypatch)
monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "0")
assert selection_config()[3] == 0
def test_selection_config_garbage_floor_warns_and_defaults(monkeypatch, caplog):
_clear_selection_env(monkeypatch)
monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "not-a-number")
with caplog.at_level("WARNING"):
assert selection_config()[3] == 40
assert any("SUMMARY_FALLBACK_MIN_SCORE" in rec.message for rec in caplog.records)
@pytest.mark.parametrize("raw,expected", [("100", 100), ("101", 100), ("-5", 0)])
def test_selection_config_floor_is_clamped(monkeypatch, raw, expected):
_clear_selection_env(monkeypatch)
monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", raw)
assert selection_config()[3] == expected