diff --git a/.env.example b/.env.example index def97d4..fe913fd 100644 --- a/.env.example +++ b/.env.example @@ -100,13 +100,11 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 NEWS_BATCH_SIZE=50 # Map-phase grading: the map model scores each article 0-100, and only blocks # with score >= SUMMARY_MIN_SCORE reach the reduce brief (best first). -# If nothing clears the bar, up to SUMMARY_FALLBACK_TOP blocks scoring at least -# SUMMARY_FALLBACK_MIN_SCORE are used; if none do, the reduce phase gets an -# empty DATA section (SUMMARY_FALLBACK_TOP=0 does the same unconditionally). +# If nothing clears the bar, the top SUMMARY_FALLBACK_TOP blocks are used +# (0 = honour the threshold and pass an empty DATA section instead). SUMMARY_MIN_SCORE=60 SUMMARY_TOP_N=12 SUMMARY_FALLBACK_TOP=3 -SUMMARY_FALLBACK_MIN_SCORE=40 SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. diff --git a/docs/news.md b/docs/news.md index 9f0a9d2..92d5342 100644 --- a/docs/news.md +++ b/docs/news.md @@ -79,11 +79,9 @@ it to 0-100, and falls back to the `Importance:` label (critical 95, high 78, medium 50, low 22, none 5) when the line is missing or unparsable — a block is never dropped and the fallback count is logged per batch. Only blocks scoring `>= SUMMARY_MIN_SCORE` (default 60) reach the reduce prompt, best first, capped -at `SUMMARY_TOP_N` (default 12). If nothing clears the bar, up to -`SUMMARY_FALLBACK_TOP` blocks (default 3) scoring at least -`SUMMARY_FALLBACK_MIN_SCORE` (default 40) are used; when none does, or when -`SUMMARY_FALLBACK_TOP=0`, the reduce phase receives an empty DATA section and -writes the empty-brief response instead of promoting noise. The reduce prompt +at `SUMMARY_TOP_N` (default 12). If nothing clears the bar the top +`SUMMARY_FALLBACK_TOP` blocks (default 3) are used so the HUD is not blank; +`SUMMARY_FALLBACK_TOP=0` passes an empty DATA section instead. The reduce prompt no longer asks for filler: it leads with the highest-scoring stories and never promotes an item above its score. Every graded article is persisted to `article_scores` (score, category, selected, model, summary_id) so the operator @@ -269,8 +267,7 @@ map. `summary_en` lands in `article_summaries.summary_text`. | `SUMMARY_MIN_SCORE` | `60` | Map-phase score a block must reach to enter the reduce brief. | | `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). | | `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. | -| `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. | -| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). | +| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. | | `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). | | `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). | | `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. | diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index 7d3dc15..d99b258 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -210,20 +210,13 @@ def parse_map_scores( def select_graded( - blocks: list[dict], - *, - min_score: int, - top_n: int, - fallback_top: int, - fallback_min_score: int = 0, + 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 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. + 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)) @@ -233,11 +226,7 @@ def select_graded( fallback_limit = max(0, int(fallback_top)) if fallback_limit <= 0: return [], False - 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 + return ordered[:fallback_limit], bool(ordered) def join_blocks(blocks: list[dict]) -> str: diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index c1daeae..2ddd023 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -54,7 +54,6 @@ 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: @@ -68,15 +67,12 @@ def _env_int(name: str, default: int) -> int: return default -def selection_config() -> tuple[int, int, int, int]: - """(min_score, top_n, fallback_top, fallback_min_score) from env, per run.""" +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)) - 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 + return min_score, top_n, fallback_top def _summary_window_minutes() -> int: @@ -393,18 +389,12 @@ def ensure_tables() -> None: def get_recent_news(window_minutes: int | None = None) -> list[dict]: - """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. - """ + """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 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; """ @@ -639,12 +629,12 @@ def summarize_news() -> None: logger.info("No new articles found in the last %s min.", window) return - min_score, top_n, fallback_top, fallback_min_score = selection_config() + min_score, top_n, fallback_top = 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, fallback_min_score=%d)...", + "min_score=%d, top_n=%d, fallback_top=%d)...", len(articles), model, BATCH_SIZE, recap, window, - min_score, top_n, fallback_top, fallback_min_score, + min_score, top_n, fallback_top, ) graded: list[dict] = [] @@ -679,11 +669,7 @@ def summarize_news() -> None: return selected, used_fallback = select_graded( - graded, - min_score=min_score, - top_n=top_n, - fallback_top=fallback_top, - fallback_min_score=fallback_min_score, + 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: @@ -691,9 +677,8 @@ def summarize_news() -> None: if used_fallback: logger.warning( "No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d " - "with score >= %d (max score %d)", - min_score, len(selected), fallback_min_score, - max(b["score"] for b in graded), + "(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)", @@ -703,9 +688,8 @@ 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, " - "fallback_min_score=%d) — reduce gets empty DATA.", - min_score, fallback_top, fallback_min_score, + "Selection is empty (min_score=%d, fallback_top=%d) — reduce gets empty DATA.", + min_score, fallback_top, ) master_raw = call_llm( diff --git a/news/summerizer/tests/test_grading.py b/news/summerizer/tests/test_grading.py index 4de4d92..811f3d0 100644 --- a/news/summerizer/tests/test_grading.py +++ b/news/summerizer/tests/test_grading.py @@ -152,63 +152,6 @@ 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) diff --git a/news/summerizer/tests/test_grading_pipeline.py b/news/summerizer/tests/test_grading_pipeline.py index 3b6f021..b78bf80 100644 --- a/news/summerizer/tests/test_grading_pipeline.py +++ b/news/summerizer/tests/test_grading_pipeline.py @@ -177,35 +177,6 @@ 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 diff --git a/news/summerizer/tests/test_summarizer.py b/news/summerizer/tests/test_summarizer.py index 708a3f5..117044f 100644 --- a/news/summerizer/tests/test_summarizer.py +++ b/news/summerizer/tests/test_summarizer.py @@ -1,19 +1,10 @@ -"""Summarizer window, recap flag, no futures injection, and grading env knobs.""" +"""Summarizer window, recap flag, and no futures injection into prompts.""" -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, ) @@ -52,164 +43,3 @@ 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