From 72757e7c51a363bb377284662e8dc85a598b6dbf Mon Sep 17 00:00:00 2001 From: Hermes Backend Date: Fri, 13 Nov 2026 21:15:05 -0500 Subject: [PATCH 01/21] feat(auth): ADMIN_COOKIE_SECURE forces the session cookie Secure Behind the cluster's HTTP origin listener Envoy normalizes X-Forwarded-Proto to http, so _is_https() never fires and the session cookie was issued without Secure. Add an explicit deploy-time flag: set_session_cookie() now marks the cookie Secure when the env var is 1/true/yes (case-insensitive, stripped) or the header inference says https. clear_session_cookie() is unchanged, SameSite stays Lax. Tests cover flag-over-http, header-without-flag, and the local-dev path; docs/auth.md and .env.example document the variable. --- .env.example | 5 +++++ app/auth.py | 18 ++++++++++++++++-- docs/auth.md | 7 +++++++ tests/test_auth.py | 41 +++++++++++++++++++++++++++++++++++++++-- 4 files changed, 67 insertions(+), 4 deletions(-) diff --git a/.env.example b/.env.example index 7e582dc..42d5c10 100644 --- a/.env.example +++ b/.env.example @@ -79,6 +79,11 @@ VESSELAPI_IN_INGEST=0 ADMIN_USER= ADMIN_PASSWORD_HASH= ADMIN_SESSION_SECRET= +# Optional: force the session cookie's Secure flag (1/true/yes) when the app is +# reached over plain HTTP behind a TLS-terminating proxy that rewrites +# X-Forwarded-Proto to http (the cluster: Cloudflare tunnel -> Cilium Gateway). +# Leave unset locally so the cookie works over http://localhost. +ADMIN_COOKIE_SECURE= # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── # Scraper crawls urls.txt continuously (default 10s between crawls). diff --git a/app/auth.py b/app/auth.py index cfdb074..58cc47a 100644 --- a/app/auth.py +++ b/app/auth.py @@ -16,7 +16,9 @@ Design notes * **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac`` and the session token is an HMAC-SHA256 signature over a base64url JSON payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and - ``Secure`` when the request arrived over https (``X-Forwarded-Proto``). + ``Secure`` when the request arrived over https (``X-Forwarded-Proto``) or + when ``ADMIN_COOKIE_SECURE`` is truthy (TLS-only deployments behind an + HTTP origin listener, where Envoy normalizes the header to ``http``). * **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer`` are rejected when the origin host differs from the request host. Requests without either header (curl, server-to-server) are allowed — the signed, @@ -281,6 +283,18 @@ def _is_https(request: Request) -> bool: return request.url.scheme == "https" +_TRUTHY = {"1", "true", "yes"} + + +def cookie_secure_forced() -> bool: + """``ADMIN_COOKIE_SECURE`` marks the deployment TLS-only. + + Read on every call so tests and restarts pick up env changes; the header + inference in :func:`_is_https` stays as the fallback. + """ + return (os.getenv("ADMIN_COOKIE_SECURE") or "").strip().lower() in _TRUTHY + + def set_session_cookie(response, request: Request, token: str) -> None: response.set_cookie( COOKIE_NAME, @@ -288,7 +302,7 @@ def set_session_cookie(response, request: Request, token: str) -> None: max_age=SESSION_TTL_SECONDS, httponly=True, samesite="lax", - secure=_is_https(request), + secure=cookie_secure_forced() or _is_https(request), path="/", ) diff --git a/docs/auth.md b/docs/auth.md index 8a7bef9..0e6d57f 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -60,6 +60,13 @@ arrived over https (`X-Forwarded-Proto`, i.e. behind Cloudflare). Signature and expiry are checked with `hmac.compare_digest`; a token for another username, or one signed with a different secret, is rejected. +Set `ADMIN_COOKIE_SECURE=1` (`true`/`yes` also work) whenever the deployment is +TLS-only but the app itself is reached over plain HTTP. In the cluster the +Cloudflare tunnel originates at the Cilium Gateway on plain HTTP and Envoy +normalizes `X-Forwarded-Proto` to `http`, so the header inference never fires +there — the flag is what makes the cookie `Secure` in the cluster. Leave it +unset for local development, where the cookie has to work over `http://localhost`. + ## Abuse controls * **Login rate limit:** 5 failed attempts per client IP (first hop of diff --git a/tests/test_auth.py b/tests/test_auth.py index 54d00bb..85f369b 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -318,7 +318,8 @@ def test_login_missing_fields_is_401_not_500(): assert resp.status_code == 401 -def test_login_success_sets_httponly_cookie(): +def test_login_success_sets_httponly_cookie(monkeypatch): + monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) resp = _login() assert resp.status_code == 200 assert resp.json() == {"authenticated": True, "admin": True} @@ -337,12 +338,48 @@ def test_login_accepts_json_body(): assert resp.json()["authenticated"] is True -def test_login_cookie_marks_secure_behind_https_proxy(): +def test_login_cookie_marks_secure_behind_https_proxy(monkeypatch): + monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) resp = _login(headers={"X-Forwarded-Proto": "https"}) assert resp.status_code == 200 assert "Secure" in resp.headers.get("set-cookie", "") +def test_login_cookie_secure_via_env_flag_over_http_origin(monkeypatch): + """ADMIN_COOKIE_SECURE is what makes the cookie Secure in the cluster: + the header arrives as ``http`` from the Cilium Gateway.""" + monkeypatch.setenv("ADMIN_COOKIE_SECURE", "1") + resp = _login(headers={"X-Forwarded-Proto": "http"}) + assert resp.status_code == 200 + raw = resp.headers.get("set-cookie", "") + assert "Secure" in raw + assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax") + assert "HttpOnly" in raw + + +@pytest.mark.parametrize("value", ["true", "TRUE", " Yes ", "yes"]) +def test_login_cookie_env_flag_accepts_truthy_spellings(monkeypatch, value): + monkeypatch.setenv("ADMIN_COOKIE_SECURE", value) + resp = _login() + assert resp.status_code == 200 + assert "Secure" in resp.headers.get("set-cookie", "") + + +@pytest.mark.parametrize("value", ["", "0", "false", "no", "off"]) +def test_login_cookie_env_flag_ignores_falsey_spellings(monkeypatch, value): + monkeypatch.setenv("ADMIN_COOKIE_SECURE", value) + resp = _login(headers={"X-Forwarded-Proto": "http"}) + assert resp.status_code == 200 + assert "Secure" not in resp.headers.get("set-cookie", "") + + +def test_login_cookie_without_header_or_flag_is_not_secure_locally(monkeypatch): + monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) + resp = _login() + assert resp.status_code == 200 + assert "Secure" not in resp.headers.get("set-cookie", "") + + def test_session_cookie_unlocks_admin_routes(no_db): login = _login() cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} From c42d375d6ce3416232c09e4918c47701c2b0ac79 Mon Sep 17 00:00:00 2001 From: backend Date: Fri, 13 Nov 2026 21:41:44 -0500 Subject: [PATCH 02/21] fix(news): drop future-dated items at ingest, hide them in /api/news wiseye.org public-affairs event listings carry pubDate 3-6 days ahead; with ORDER BY timestamp DESC they pinned the top of the feed for a week and made the news list look frozen. - PostgresPipeline drops items whose parsed publish date is >2h in the future, counts future_dated_dropped (stats + one INFO line per run). Unparseable dates keep the old behaviour (kept, timestamped now()). - GET /api/news filters timestamp > now() in the query while still returning timestamp IS NULL rows; limit/offset/domain/since unchanged. - docs/news.md documents the guard. - tests: pipeline drop/keep unit tests, API future-row exclusion + limit. --- app/main.py | 7 +- docs/news.md | 5 +- news/scraper/newsScraper/pipelines.py | 52 +++++++++++++++ tests/test_api_news.py | 22 ++++++- tests/test_news_scraper.py | 93 +++++++++++++++++++++++++++ 5 files changed, 176 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index dd799d7..4f466ba 100644 --- a/app/main.py +++ b/app/main.py @@ -1207,7 +1207,12 @@ async def list_news( ): """Most recent scraped news articles (newest first).""" async with async_session() as session: - stmt = select(articles).order_by( + stmt = select(articles).where( + or_( + articles.c.timestamp.is_(None), + articles.c.timestamp <= func.now(), + ) + ).order_by( articles.c.timestamp.desc().nullslast() ) if domain: diff --git a/docs/news.md b/docs/news.md index d94d29f..79d6c6f 100644 --- a/docs/news.md +++ b/docs/news.md @@ -43,7 +43,10 @@ feeds (`GET /api/news` exact key set is unchanged on purpose). URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed directly), follows each `` link, extracts the main article body, and the `PostgresPipeline` writes to `articles` with URL-based dedup - (`ON CONFLICT (url) DO NOTHING`). + (`ON CONFLICT (url) DO NOTHING`). Items whose parsed publish date is more + than 2 hours in the future are dropped at ingest (`future_dated_dropped`) + and never surface via `/api/news`, which additionally hides any + `articles.timestamp > now()` row until its date arrives. 2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs `summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00 diff --git a/news/scraper/newsScraper/pipelines.py b/news/scraper/newsScraper/pipelines.py index 68cad97..2629372 100644 --- a/news/scraper/newsScraper/pipelines.py +++ b/news/scraper/newsScraper/pipelines.py @@ -3,10 +3,49 @@ # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html +import datetime import logging import psycopg2 import os from scrapy.exceptions import DropItem + +log = logging.getLogger(__name__) + +# Feed items dated further ahead than this are event listings (or clock skew +# from the source), not news. Dropping them keeps `ORDER BY timestamp DESC` +# from pinning the top of /api/news for days. See docs/news.md. +FUTURE_TOLERANCE = datetime.timedelta(hours=2) + + +def _parsed_timestamp(value): + """Return an aware UTC datetime for an item timestamp, or None. + + None means "could not parse" — callers must keep such items, exactly as + before this guard existed (undated items currently get now() upstream). + """ + if isinstance(value, datetime.datetime): + ts = value + elif isinstance(value, str) and value.strip(): + try: + ts = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00")) + except ValueError: + return None + else: + return None + if ts.tzinfo is None: + ts = ts.replace(tzinfo=datetime.timezone.utc) + return ts.astimezone(datetime.timezone.utc) + + +def is_future_dated(value, now=None, tolerance=FUTURE_TOLERANCE): + """True when a parsed publish timestamp is more than `tolerance` ahead.""" + ts = _parsed_timestamp(value) + if ts is None: + return False + now = now or datetime.datetime.now(datetime.timezone.utc) + return ts > now + tolerance + + class PostgresPipeline: def __init__(self, db_config): @@ -14,6 +53,8 @@ class PostgresPipeline: self.db_config = db_config # 2. Initialize the set here so it exists when process_item is called self.seen_urls = set() + # 3. Future-dated drops, reported once per run in close_spider() + self.future_dated_dropped = 0 @classmethod def from_crawler(cls, crawler): @@ -54,6 +95,12 @@ class PostgresPipeline: def process_item(self, item, spider): url = item['url'] + if is_future_dated(item.get('timestamp')): + self.future_dated_dropped += 1 + stats = getattr(getattr(spider, 'crawler', None), 'stats', None) + if stats is not None: + stats.inc_value('future_dated_dropped') + raise DropItem(f"Future-dated item: {url}") if url in self.seen_urls: raise DropItem(f"Duplicate URL (in-memory): {url}") self.seen_urls.add(url) @@ -82,6 +129,11 @@ class PostgresPipeline: raise def close_spider(self, spider): + if self.future_dated_dropped: + spider.logger.info( + "Dropped %d future-dated item(s) (>%s ahead)", + self.future_dated_dropped, FUTURE_TOLERANCE, + ) self.cur.close() self.connection.close() diff --git a/tests/test_api_news.py b/tests/test_api_news.py index 0ba569d..d71c853 100644 --- a/tests/test_api_news.py +++ b/tests/test_api_news.py @@ -10,7 +10,7 @@ from __future__ import annotations import asyncio import os -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone import asyncpg import httpx @@ -157,6 +157,26 @@ def test_api_news_since_filter(clean_news): assert body[0]["title"] == "after" +@requires_db +def test_api_news_excludes_future_dated_rows(clean_news): + """Future-dated event listings must not pin the top of the feed.""" + now = datetime.now(timezone.utc) + future = now + timedelta(days=5) + recent = now - timedelta(hours=1) + _seed_article("recent", "https://a.example/recent", "a.example", recent.isoformat()) + _seed_article("future", "https://a.example/future", "a.example", future.isoformat()) + + body = _get("/api/news").json() + assert [a["title"] for a in body] == ["recent"] + + # limit still caps the (post-filter) result set + _seed_article("recent2", "https://a.example/recent2", "a.example", (now - timedelta(hours=2)).isoformat()) + _seed_article("recent3", "https://a.example/recent3", "a.example", (now - timedelta(hours=3)).isoformat()) + limited = _get("/api/news?limit=2").json() + assert [a["title"] for a in limited] == ["recent", "recent2"] + + + @requires_db def test_api_news_summaries_contract(clean_news): _seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00") diff --git a/tests/test_news_scraper.py b/tests/test_news_scraper.py index b2b3817..ac335c2 100644 --- a/tests/test_news_scraper.py +++ b/tests/test_news_scraper.py @@ -2,9 +2,12 @@ from __future__ import annotations +import datetime as _dt import sys from pathlib import Path +import pytest + ROOT = Path(__file__).resolve().parent.parent _SCRAPER = ROOT / "news/scraper" if str(_SCRAPER) not in sys.path: @@ -40,3 +43,93 @@ def test_spider_skips_audio_before_request(): assert "is_audio_url" in src assert "article_timestamp" in src assert "datetime.datetime.now()" not in src + + +# ── future-dated guard (ingest) ─────────────────────────────────────────── + +class _FakeCursor: + rowcount = 1 + + def __init__(self): + self.executed = [] + + def execute(self, sql, params=None): + self.executed.append((sql, params)) + + +class _FakeConnection: + def commit(self): + pass + + def rollback(self): + pass + + +class _FakeStats: + def __init__(self): + self.values = {} + + def inc_value(self, key, count=1): + self.values[key] = self.values.get(key, 0) + count + + +class _FakeSpider: + class _Logger: + def info(self, *a, **kw): + pass + + def error(self, *a, **kw): + pass + + def __init__(self): + self.logger = self._Logger() + self.crawler = type("C", (), {"stats": _FakeStats()})() + + +def _pipeline(): + from newsScraper.pipelines import PostgresPipeline + + pipe = PostgresPipeline(db_config={}) + pipe.cur = _FakeCursor() + pipe.connection = _FakeConnection() + return pipe + + +def _item(ts: _dt.datetime) -> dict: + return { + "title": "t", + "url": f"https://a.example/{ts.isoformat()}", + "text": "body", + "domain": "a.example", + "timestamp": ts.isoformat(), + } + + +def test_pipeline_drops_future_dated_item(): + from scrapy.exceptions import DropItem + + pipe = _pipeline() + spider = _FakeSpider() + future = _dt.datetime.now(_dt.timezone.utc) + _dt.timedelta(days=5) + with pytest.raises(DropItem): + pipe.process_item(_item(future), spider) + assert pipe.future_dated_dropped == 1 + assert spider.crawler.stats.values["future_dated_dropped"] == 1 + assert pipe.cur.executed == [] # never reached the INSERT + + +def test_pipeline_keeps_recent_item(): + pipe = _pipeline() + spider = _FakeSpider() + recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(days=1) + assert pipe.process_item(_item(recent), spider)["domain"] == "a.example" + assert pipe.future_dated_dropped == 0 + assert len(pipe.cur.executed) == 1 + + +def test_pipeline_keeps_unparseable_timestamp(): + from newsScraper.pipelines import is_future_dated + + assert is_future_dated("not a date") is False + assert is_future_dated(None) is False + From 853e87b7c5c1bb86c36e1149a96dd6fe3bc18bac Mon Sep 17 00:00:00 2001 From: hermes-backend Date: Fri, 13 Nov 2026 21:47:30 -0500 Subject: [PATCH 03/21] 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 --- .env.example | 7 + alembic/versions/012_article_scores.py | 39 ++++ docs/news.md | 28 ++- news/summerizer/intel.py | 132 +++++++++++- news/summerizer/summarizer.py | 192 ++++++++++++++--- news/summerizer/tests/test_grading.py | 174 +++++++++++++++ .../summerizer/tests/test_grading_pipeline.py | 202 ++++++++++++++++++ news/summerizer/tests/test_prompts.py | 38 +++- 8 files changed, 775 insertions(+), 37 deletions(-) create mode 100644 alembic/versions/012_article_scores.py create mode 100644 news/summerizer/tests/test_grading.py create mode 100644 news/summerizer/tests/test_grading_pipeline.py diff --git a/.env.example b/.env.example index 42d5c10..fe913fd 100644 --- a/.env.example +++ b/.env.example @@ -98,6 +98,13 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 # Hermes-4.3-36B remains after a Postgres miss. Env wins when set. # SUMMARY_MODEL= 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, 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_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/alembic/versions/012_article_scores.py b/alembic/versions/012_article_scores.py new file mode 100644 index 0000000..853ded7 --- /dev/null +++ b/alembic/versions/012_article_scores.py @@ -0,0 +1,39 @@ +"""article_scores: per-article map-phase grades for threshold tuning + +Revision ID: 012_article_scores +Revises: 011_geofence_alerts_fence +Create Date: 2026-11-13 +""" + +from alembic import op + +revision = "012_article_scores" +down_revision = "011_geofence_alerts_fence" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + """ + 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) + ) + """ + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_article_scores_summary " + "ON article_scores (summary_id)" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_article_scores_summary") + op.execute("DROP TABLE IF EXISTS article_scores") diff --git a/docs/news.md b/docs/news.md index d64b31d..d5e00bb 100644 --- a/docs/news.md +++ b/docs/news.md @@ -60,8 +60,29 @@ if `article_summaries` already has a row in the last interval, the summarizer The `articles` and `article_summaries` tables are created by the idempotent alembic migration `003_news` (also created by the scraper's own -`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items`. -Container startup order doesn't matter. +`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items` and +`article_scores` is `012_article_scores` (also created by the summarizer's own +`ensure_tables()`). Container startup order doesn't matter. + +## Grading and selection + +The map phase grades every article 0-100 against the rubric in the map prompt +(90-100 breaking geopolitical/military/security or major disaster, 70-89 +significant national/international news, 40-69 notable regional/economic/tech/ +health, 10-39 routine crime and local interest, 0-9 noise: sport, celebrity, +entertainment, market tape, promotional and event-calendar listings). The +summarizer parses the first `Score:` line in each `Article :` block, clamps +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 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 +can tune the thresholds against real data. ## Keys and Settings @@ -240,6 +261,9 @@ map. `summary_en` lands in `article_summaries.summary_text`. | `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. | | `SUMMARY_MODEL` | `Hermes-4.3-36B` | Compose default. Operator-facing choice is Settings → `app_settings.SUMMARY_MODEL`. | | `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch (compose maps to container `BATCH_SIZE`). | +| `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_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). | diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index 1f9874c..d99b258 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -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 `` 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) diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index acc1262..2ddd023 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -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__": diff --git a/news/summerizer/tests/test_grading.py b/news/summerizer/tests/test_grading.py new file mode 100644 index 0000000..811f3d0 --- /dev/null +++ b/news/summerizer/tests/test_grading.py @@ -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 diff --git a/news/summerizer/tests/test_grading_pipeline.py b/news/summerizer/tests/test_grading_pipeline.py new file mode 100644 index 0000000..b78bf80 --- /dev/null +++ b/news/summerizer/tests/test_grading_pipeline.py @@ -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) diff --git a/news/summerizer/tests/test_prompts.py b/news/summerizer/tests/test_prompts.py index 954e5b3..048e472 100644 --- a/news/summerizer/tests/test_prompts.py +++ b/news/summerizer/tests/test_prompts.py @@ -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(): From 57c0444a69265c86344160b9f42558dae1baa802 Mon Sep 17 00:00:00 2001 From: backend Date: Fri, 13 Nov 2026 21:56:46 -0500 Subject: [PATCH 04/21] 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. --- .env.example | 6 +- docs/news.md | 11 +- news/summerizer/intel.py | 19 +- news/summerizer/summarizer.py | 40 ++-- news/summerizer/tests/test_grading.py | 57 ++++++ .../summerizer/tests/test_grading_pipeline.py | 29 +++ news/summerizer/tests/test_summarizer.py | 172 +++++++++++++++++- 7 files changed, 311 insertions(+), 23 deletions(-) diff --git a/.env.example b/.env.example index fe913fd..def97d4 100644 --- a/.env.example +++ b/.env.example @@ -100,11 +100,13 @@ 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, the top SUMMARY_FALLBACK_TOP blocks are used -# (0 = honour the threshold and pass an empty DATA section instead). +# 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). 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 92d5342..9f0a9d2 100644 --- a/docs/news.md +++ b/docs/news.md @@ -79,9 +79,11 @@ 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 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 +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 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 @@ -267,7 +269,8 @@ 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_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. | +| `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). | | `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 d99b258..7d3dc15 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -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: diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index 2ddd023..c1daeae 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -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( diff --git a/news/summerizer/tests/test_grading.py b/news/summerizer/tests/test_grading.py index 811f3d0..4de4d92 100644 --- a/news/summerizer/tests/test_grading.py +++ b/news/summerizer/tests/test_grading.py @@ -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) diff --git a/news/summerizer/tests/test_grading_pipeline.py b/news/summerizer/tests/test_grading_pipeline.py index b78bf80..3b6f021 100644 --- a/news/summerizer/tests/test_grading_pipeline.py +++ b/news/summerizer/tests/test_grading_pipeline.py @@ -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 diff --git a/news/summerizer/tests/test_summarizer.py b/news/summerizer/tests/test_summarizer.py index 117044f..708a3f5 100644 --- a/news/summerizer/tests/test_summarizer.py +++ b/news/summerizer/tests/test_summarizer.py @@ -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 From d40244900e61171dc929eae3a919de95c312f174 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 13 Nov 2026 22:14:44 -0500 Subject: [PATCH 05/21] feat(summarizer): collapse syndicated wire copies before selection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The map phase grades every article, but a single wire story arrives from many station domains with an identical headline (the measured run selected 12 blocks that were only two stories, then produced a ticker with five summit rows and one FAA row). Dedupe now runs before the threshold/cap, so SUMMARY_TOP_N buys distinct stories. - intel.py: pure `dedupe_blocks(blocks, *, similarity, enabled)` plus `normalize_title` / `title_similarity`. Titles are lowercased, punctuation flattened and a short digit-free trailing source suffix (" - KCCI", " | CNN", " — AP") dropped; blocks match on equal normalised titles or word-set Jaccard / word-sequence difflib ratio >= similarity (default 0.85). Best score wins the group (ties -> earliest), matching is against the representative only (no transitive chaining), and differing categories or differing numbers never merge. Blocks now carry their article title. - summarizer.py: dedupe graded blocks before select_graded() and log `dedupe 21 -> 9 (kept 9, duplicates 12)`; SUMMARY_DEDUPE=0 skips it, SUMMARY_DEDUPE_SIMILARITY tunes it. persist_article_scores() still writes one row per graded article, with duplicates selected=false and duplicate_of pointing at the surviving article id. - article_scores.duplicate_of INTEGER NULL in ensure_tables() and alembic 013 (upgrade/downgrade verified against Postgres 16). - docs/news.md + .env.example document both knobs. Replaying the observed summary id=6 (21 graded, 9 distinct titles) now keeps 9 and, at min_score=60/top_n=12, selects 2 — the 11 dropped copies that scored >= 60 are stored selected=false with a duplicate_of pointer. --- .env.example | 10 + .../013_article_scores_duplicate_of.py | 23 + docs/news.md | 17 + news/summerizer/intel.py | 197 ++++++++ news/summerizer/summarizer.py | 89 +++- news/summerizer/tests/test_dedupe.py | 432 ++++++++++++++++++ 6 files changed, 757 insertions(+), 11 deletions(-) create mode 100644 alembic/versions/013_article_scores_duplicate_of.py create mode 100644 news/summerizer/tests/test_dedupe.py diff --git a/.env.example b/.env.example index def97d4..b23921c 100644 --- a/.env.example +++ b/.env.example @@ -107,6 +107,16 @@ SUMMARY_MIN_SCORE=60 SUMMARY_TOP_N=12 SUMMARY_FALLBACK_TOP=3 SUMMARY_FALLBACK_MIN_SCORE=40 +# Syndication dedupe: the same wire story arrives from many station domains +# (kcci.com, wtae.com, …) with an identical headline. Copies are collapsed +# before the threshold/cap, so SUMMARY_TOP_N buys distinct stories: normalised +# titles (lowercase, trailing " - KCCI"/" | CNN"/" — AP" source suffix dropped) +# count as one story when they are equal or >= SUMMARY_DEDUPE_SIMILARITY alike. +# The highest-scoring copy represents the story; the rest are still written to +# article_scores with selected=false and duplicate_of = the surviving article id. +# Set SUMMARY_DEDUPE=0 to skip dedupe entirely (old behaviour). +SUMMARY_DEDUPE=1 +SUMMARY_DEDUPE_SIMILARITY=0.85 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/alembic/versions/013_article_scores_duplicate_of.py b/alembic/versions/013_article_scores_duplicate_of.py new file mode 100644 index 0000000..2fcfb8b --- /dev/null +++ b/alembic/versions/013_article_scores_duplicate_of.py @@ -0,0 +1,23 @@ +"""article_scores.duplicate_of: link a syndicated copy to its representative + +Revision ID: 013_article_scores_duplicate_of +Revises: 012_article_scores +Create Date: 2026-11-13 +""" + +from alembic import op + +revision = "013_article_scores_duplicate_of" +down_revision = "012_article_scores" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER" + ) + + +def downgrade() -> None: + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS duplicate_of") diff --git a/docs/news.md b/docs/news.md index 9f0a9d2..4d4c545 100644 --- a/docs/news.md +++ b/docs/news.md @@ -89,6 +89,21 @@ promotes an item above its score. Every graded article is persisted to `article_scores` (score, category, selected, model, summary_id) so the operator can tune the thresholds against real data. +Syndicated wire copy is collapsed **before** the threshold and cap, so +`SUMMARY_TOP_N` counts distinct stories instead of stations: the same headline +carried by seven Hearst domains is one story, not seven. Titles are normalised +first (lowercase, punctuation flattened, a trailing ` - KCCI` / ` | CNN` / +` — AP` source suffix dropped when it is short and digit-free), then two blocks +are the same story when the normalised titles are equal or at least +`SUMMARY_DEDUPE_SIMILARITY` similar (default 0.85; word-set Jaccard or +word-sequence `difflib` ratio). The highest-scoring copy represents the story +(ties → earliest); differing `category` values and titles that disagree on any +number are never merged. Duplicates are still written to `article_scores` with +`selected=false` and `duplicate_of` = the surviving `article_id`, so nothing is +lost for tuning. `SUMMARY_DEDUPE=0` disables dedupe entirely; raising +`SUMMARY_DEDUPE_SIMILARITY` toward 0.95 makes it stricter. Dedupe is pure string +work — no extra LLM call. + ## Keys and Settings - **`NOUS_API_KEY`** — paste in the dashboard **Keys** UI (`api_keys` / @@ -270,6 +285,8 @@ map. `summary_en` lands in `article_summaries.summary_text`. | `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_DEDUPE` | `1` | Collapse syndicated wire copies before selection; `0` skips dedupe entirely. | +| `SUMMARY_DEDUPE_SIMILARITY` | `0.85` | Normalised-title similarity at which two blocks count as the same story (1.0 = verbatim only). | | `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). | | `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). | diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index 7d3dc15..5cdf13c 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -2,6 +2,7 @@ from __future__ import annotations +import difflib import json import re @@ -193,6 +194,7 @@ def parse_map_scores( "n": n, "article": article, "article_id": article.get("id"), + "title": article.get("title"), "score": score, "importance": importance, "category": _category_from_block(block_text), @@ -243,3 +245,198 @@ def select_graded( 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) + + +# ── Syndication dedupe (pure string work — no LLM, no DB) ────────────────── + +DEFAULT_DEDUPE_SIMILARITY = 0.85 + +# Wire copy carries the station at the end of the headline: " - KCCI", " | CNN". +_SOURCE_SEPARATORS = (" - ", " | ", " — ", " – ") +_MAX_SUFFIX_CHARS = 40 +_MAX_SUFFIX_WORDS = 4 +_NON_ALNUM_RE = re.compile(r"[^a-z0-9]+") +_DIGIT_RE = re.compile(r"\d") + + +def normalize_title(title) -> str: + """Comparable headline form: lowercase, source suffix stripped, words only. + + A trailing `` - KCCI`` / `` | CNN`` / `` — AP`` marker is removed when the + tail is short (<= 40 chars and <= 4 words) **and carries no digits**, so + ``Story - KCCI`` and ``Story | WTAE`` land on the same key while serial + titles (``… – Part 1`` / ``… – Part 2``, ``… — Day 5``) stay distinct. + Titles that are None, empty or non-string normalise to ``""`` and never + match anything. + """ + if title is None: + return "" + if not isinstance(title, str): + title = str(title) + text = title.strip().lower() + cut = -1 + for separator in _SOURCE_SEPARATORS: + idx = text.rfind(separator) + if idx <= 0: + continue + tail = text[idx + len(separator):].strip() + if ( + len(tail) <= _MAX_SUFFIX_CHARS + and 0 < len(tail.split()) <= _MAX_SUFFIX_WORDS + and not _DIGIT_RE.search(tail) + ): + cut = max(cut, idx) + if cut > 0: + text = text[:cut] + return " ".join(_NON_ALNUM_RE.sub(" ", text).split()) + + +def title_similarity(normalised_left: str, normalised_right: str) -> float: + """0..1 story-similarity of two already-normalised titles. + + Max of word-set Jaccard (word order and repetition do not matter) and the + ``difflib`` ratio over the *word sequence* (so near-verbatim rewrites + score high, while short headlines differing only in a name — "story 1" vs + "story 2", "storm hits Texas" vs "storm hits Tennessee" — stay low). + """ + if not normalised_left or not normalised_right: + return 0.0 + if normalised_left == normalised_right: + return 1.0 + words_left = normalised_left.split() + words_right = normalised_right.split() + set_left, set_right = set(words_left), set(words_right) + union = set_left | set_right + jaccard = len(set_left & set_right) / len(union) if union else 0.0 + ratio = difflib.SequenceMatcher(None, words_left, words_right).ratio() + return max(jaccard, ratio) + + +def _block_title(block: dict): + """Title of a graded block: the parsed key, else the nested article row.""" + title = block.get("title") + if title is None: + article = block.get("article") + if isinstance(article, dict): + title = article.get("title") + return title + + +def _block_score(block: dict) -> int: + try: + return int(block.get("score") or 0) + except (TypeError, ValueError): + return 0 + + +def _block_position(block: dict, fallback: int) -> int: + position = block.get("position") + return position if isinstance(position, int) else fallback + + +def _categories_conflict(left: dict, right: dict) -> bool: + """True when both blocks carry a category and the two differ.""" + cat_left = str(left.get("category") or "").strip().lower() + cat_right = str(right.get("category") or "").strip().lower() + return bool(cat_left) and bool(cat_right) and cat_left != cat_right + + +def _numbers_conflict(left: str, right: str) -> bool: + """True when the two titles disagree on any number. + + Syndicated wire copy is verbatim, so a differing figure ("… – Part 1" vs + "… – Part 2", "12 dead" vs "21 dead", horoscope date boilerplate) means a + different story — never collapse it on string similarity alone. + """ + digits_left = {word for word in left.split() if _DIGIT_RE.search(word)} + digits_right = {word for word in right.split() if _DIGIT_RE.search(word)} + return digits_left != digits_right + + +def dedupe_blocks( + blocks: list[dict], + *, + similarity: float = DEFAULT_DEDUPE_SIMILARITY, + enabled: bool = True, +) -> tuple[list[dict], dict]: + """Collapse syndicated copies of one story into a single representative block. + + Blocks are visited best-score-first (ties -> earliest position), so each + cluster's representative is its highest-scoring block and a dropped block + never survives. Matching is against the representative only (star + clustering, no transitive chaining); two titles match when their normalised + forms are equal or ``title_similarity`` clears ``similarity``. Blocks whose + categories are both set and different are never merged, and neither are + titles that disagree on any number (wire copy is verbatim; a different + figure is a different story). Blocks without a usable title stay unique. + Never raises: empty/None input and malformed blocks are tolerated. + + Returns ``(kept_blocks, stats)``; kept blocks keep their original order. + ``stats["duplicate_blocks"]`` holds one record per dropped block:: + + {"index", "article_id", "position", "score", "title", + "duplicate_of", "duplicate_of_position", "similarity", "block"} + """ + items = [block for block in (blocks or []) if isinstance(block, dict)] + try: + threshold = float(similarity) + except (TypeError, ValueError): + threshold = DEFAULT_DEDUPE_SIMILARITY + threshold = min(1.0, max(0.0, threshold)) + stats = { + "input": len(items), + "kept": len(items), + "duplicates": 0, + "threshold": threshold, + "duplicate_blocks": [], + } + if not enabled or len(items) < 2: + return list(items), stats + + ranked = sorted( + range(len(items)), + key=lambda i: (-_block_score(items[i]), _block_position(items[i], i), i), + ) + # groups: representative index -> normalised representative title + groups: list[dict] = [] + for index in ranked: + block = items[index] + norm = normalize_title(_block_title(block)) + match: tuple[dict, float] | None = None + if norm: + for group in groups: + rep_norm = group["norm"] + if ( + not rep_norm + or _categories_conflict(block, items[group["index"]]) + or _numbers_conflict(norm, rep_norm) + ): + continue + score = 1.0 if norm == rep_norm else title_similarity(norm, rep_norm) + if score >= threshold: + match = (group, score) + break + if match is None: + groups.append({"index": index, "norm": norm}) + continue + group, score = match + rep = items[group["index"]] + stats["duplicate_blocks"].append( + { + "index": index, + "article_id": block.get("article_id"), + "position": _block_position(block, index), + "score": _block_score(block), + "title": _block_title(block), + "duplicate_of": rep.get("article_id"), + "duplicate_of_position": _block_position(rep, group["index"]), + "similarity": round(score, 4), + "block": block, + } + ) + + dropped = {record["index"] for record in stats["duplicate_blocks"]} + kept = [block for index, block in enumerate(items) if index not in dropped] + stats["kept"] = len(kept) + stats["duplicates"] = len(stats["duplicate_blocks"]) + return kept, stats diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index c1daeae..b1d9c85 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -14,6 +14,12 @@ of each summarize_news() — env wins, else api_keys / app_settings: NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY') NOUS_BASE_URL default https://inference-api.nousresearch.com/v1 SUMMARY_MODEL default Hermes-4.3-36B (else app_settings) + SUMMARY_MIN_SCORE map-score a block needs to reach the reduce brief (60) + SUMMARY_TOP_N max distinct blocks passed to reduce (12) + SUMMARY_FALLBACK_TOP blocks used when nothing clears MIN_SCORE (3) + SUMMARY_FALLBACK_MIN_SCORE score floor for that fallback set (40) + SUMMARY_DEDUPE "0" disables syndication dedupe (default on) + SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85) BATCH_SIZE articles per map-phase batch (default 50) SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set) NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt) @@ -31,7 +37,15 @@ from zoneinfo import ZoneInfo import psycopg2 -from intel import join_blocks, parse_map_scores, parse_reduce_json, select_graded, select_map, select_ticker +from intel import ( + dedupe_blocks, + 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") @@ -56,6 +70,10 @@ DEFAULT_SUMMARY_TOP_N = 12 DEFAULT_SUMMARY_FALLBACK_TOP = 3 DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40 +# Syndication dedupe (pure string work, runs before the threshold/cap). +DEFAULT_SUMMARY_DEDUPE_SIMILARITY = 0.85 +_FALSY = ("0", "false", "no", "off") + def _env_int(name: str, default: int) -> int: raw = (os.getenv(name) or "").strip() @@ -68,6 +86,26 @@ def _env_int(name: str, default: int) -> int: return default +def _env_float(name: str, default: float) -> float: + raw = (os.getenv(name) or "").strip() + if not raw: + return default + try: + return float(raw) + except ValueError: + logger.warning("Invalid %s=%r — using default %s", name, raw, default) + return default + + +def dedupe_config() -> tuple[bool, float]: + """(enabled, similarity) from env. SUMMARY_DEDUPE=0 skips dedupe entirely.""" + enabled = (os.getenv("SUMMARY_DEDUPE") or "1").strip().lower() not in _FALSY + similarity = _env_float( + "SUMMARY_DEDUPE_SIMILARITY", DEFAULT_SUMMARY_DEDUPE_SIMILARITY + ) + return enabled, min(1.0, max(0.0, similarity)) + + 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))) @@ -375,9 +413,11 @@ def ensure_tables() -> None: category TEXT, selected BOOLEAN NOT NULL, model TEXT, + duplicate_of INTEGER, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (article_id, created_at) ); + ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER; CREATE INDEX IF NOT EXISTS ix_article_scores_summary ON article_scores (summary_id); """ @@ -544,6 +584,9 @@ def persist_article_scores( ) -> None: """Insert one article_scores row per graded article (selected true/false). + Syndication duplicates are written too, with ``selected=false`` and + ``duplicate_of`` pointing at the surviving article id — the representative + carries the selection even when the copy itself scores above the bar. Best-effort: a failure here is logged and never aborts the run. """ rows = [] @@ -551,14 +594,18 @@ def persist_article_scores( article_id = block.get("article_id") if article_id is None: continue + duplicate_of = block.get("duplicate_of") + if not isinstance(duplicate_of, int): + duplicate_of = None rows.append( ( article_id, summary_id, int(block.get("score") or 0), block.get("category"), - bool(block.get("selected")), + bool(block.get("selected")) and duplicate_of is None, model, + duplicate_of, ) ) if not rows: @@ -568,16 +615,17 @@ def persist_article_scores( cur = conn.cursor() cur.executemany( "INSERT INTO article_scores " - "(article_id, summary_id, score, category, selected, model) " - "VALUES (%s, %s, %s, %s, %s, %s)", + "(article_id, summary_id, score, category, selected, model, duplicate_of) " + "VALUES (%s, %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, + "article_scores persisted rows=%d selected=%d duplicates=%d summary_id=%s", + len(rows), sum(1 for r in rows if r[4]), + sum(1 for r in rows if r[6] is not None), summary_id, ) except Exception as exc: # noqa: BLE001 logger.error("Error persisting article_scores (run continues): %s", exc) @@ -678,16 +726,35 @@ def summarize_news() -> None: logger.warning("No article blocks parsed from the map phase — nothing to reduce.") return + dedupe_enabled, dedupe_similarity = dedupe_config() + distinct, dedupe_stats = dedupe_blocks( + graded, similarity=dedupe_similarity, enabled=dedupe_enabled + ) + duplicate_blocks = [record["block"] for record in dedupe_stats["duplicate_blocks"]] + for record in dedupe_stats["duplicate_blocks"]: + record["block"]["duplicate_of"] = record["duplicate_of"] + if dedupe_enabled: + logger.info( + "dedupe %d -> %d (kept %d, duplicates %d)", + dedupe_stats["input"], dedupe_stats["kept"], + dedupe_stats["kept"], dedupe_stats["duplicates"], + ) + else: + logger.info("dedupe skipped (SUMMARY_DEDUPE=0)") + selected, used_fallback = select_graded( - graded, + distinct, 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: + for block in distinct: block["selected"] = block["position"] in selected_positions + for block in duplicate_blocks: + # The representative carries the selection; a wire copy never does. + block["selected"] = False if used_fallback: logger.warning( "No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d " @@ -696,8 +763,8 @@ def summarize_news() -> None: 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], + "selected %d/%d distinct articles for reduce (scores=%s)", + len(selected), len(distinct), [b["score"] for b in selected], ) final_input = join_blocks(selected) @@ -726,7 +793,7 @@ def summarize_news() -> None: parsed["map_items"], kind="daily_recap" if recap else "interval", ) - persist_article_scores(graded, summary_id=summary_id, model=model) + persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model) if __name__ == "__main__": diff --git a/news/summerizer/tests/test_dedupe.py b/news/summerizer/tests/test_dedupe.py new file mode 100644 index 0000000..1f2ae87 --- /dev/null +++ b/news/summerizer/tests/test_dedupe.py @@ -0,0 +1,432 @@ +"""Syndication dedupe: collapse wire copies before the threshold/cap runs.""" + +from __future__ import annotations + +import json + +import pytest + +import summarizer +from intel import ( + DEFAULT_DEDUPE_SIMILARITY, + dedupe_blocks, + normalize_title, + select_graded, + title_similarity, +) + +# Real titles/scores/categories/ids from summary_id=6 (the measured defect): +# 21 graded articles, 9 distinct titles, 12 of them two wire stories. +OBSERVED_RUN = [ + (95, "www.kcci.com", "politics", 17263, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (95, "www.wyff4.com", "politics", 18546, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (95, "www.wtae.com", "politics", 18550, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.koat.com", "politics", 17272, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.ketv.com", "politics", 17291, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.wlky.com", "politics", 18205, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.wbaltv.com", "politics", 18297, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (75, "www.wlky.com", "other", 23748, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (75, "www.wtae.com", "other", 24029, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.kcci.com", "other", 22643, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.ketv.com", "other", 22664, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.koat.com", "other", 22683, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.wbaltv.com", "other", 23708, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (55, "www.wlky.com", "environment/disaster", 23943, + "Wild video shows the moment a tanker struck a docked cruise ship in New Orleans"), + (55, "www.wyff4.com", "other", 24087, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (45, "www.straitstimes.com", "other", 21227, + "Over 600 personnel take part in multi-agency exercise at RTS Link Woodlands North station"), + (30, "nypost.com", "crime", 16888, + "Monster ex-cop sentenced to chemical castration for raping young kids: “We will take his manhood!”"), + (5, "www.excelsior.com.mx", "other", 17414, + ""), + (5, "nypost.com", "sport", 22376, + "Rangers’ Dylan Garand gets full-circle moment in return to British Columbia"), + (5, "nypost.com", "sport", 22427, + "Chargers get harsh reality check from edge rusher as frustration builds: ‘Walk upstairs and ask them’"), + (5, "www.channelnewsasia.com", "sport", 23026, + "Svitolina says daughter remains priority after split from Monfils"), +] + + +def _blocks(rows) -> list[dict]: + return [ + { + "position": index, + "article_id": article_id, + "score": score, + "category": category, + "domain": domain, + "title": title, + "text": f"Article {index + 1}:\n- Score: {score}\n- Title: {title}", + } + for index, (score, domain, category, article_id, title) in enumerate(rows) + ] + + +def _story(title, *, score=90, article_id=None, category="politics", domain="ex.com", position=0): + return { + "position": position, + "article_id": article_id, + "score": score, + "category": category, + "domain": domain, + "title": title, + "text": f"Article {position + 1}:\n- Score: {score}", + } + + +# ── title normalisation ─────────────────────────────────────────────────── + +@pytest.mark.parametrize( + "title,expected", + [ + ("Big story - KCCI", "big story"), + ("Big story | CNN", "big story"), + ("Big story — AP", "big story"), + ("Big story – AP", "big story"), + (" Big STORY!! ", "big story"), + ("Trump–Xi–Putin summit", "trump xi putin summit"), + ], +) +def test_normalize_title(title, expected): + assert normalize_title(title) == expected + + +@pytest.mark.parametrize("title", [None, "", " ", 12345, ["not", "a", "title"]]) +def test_normalize_title_never_raises(title): + assert isinstance(normalize_title(title), str) + + +def test_serial_titles_are_not_treated_as_a_source_suffix(): + assert normalize_title("Governor's Board – Part 1") != normalize_title( + "Governor's Board – Part 2" + ) + + +# ── grouping ────────────────────────────────────────────────────────────── + +def test_exact_title_duplicates_collapse_to_the_best_scoring_copy(): + blocks = _blocks( + [ + (70, "a.com", "politics", 1, "Storm hits the coast"), + (95, "b.com", "politics", 2, "Storm hits the coast - KCCI"), + (80, "c.com", "politics", 3, "Storm hits the coast"), + ] + ) + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 1 + assert kept[0]["article_id"] == 2 # highest score wins, not the earliest + assert stats["input"] == 3 and stats["kept"] == 1 and stats["duplicates"] == 2 + assert {record["article_id"] for record in stats["duplicate_blocks"]} == {1, 3} + assert all( + record["duplicate_of"] == 2 for record in stats["duplicate_blocks"] + ) + assert all( + record["duplicate_of_position"] == 1 for record in stats["duplicate_blocks"] + ) + + +def test_hearst_style_syndication_set_collapses_to_one(): + domains = [ + "www.kcci.com", "www.wtae.com", "www.wyff4.com", "www.wbaltv.com", + "www.koat.com", "www.ketv.com", "www.wlky.com", + ] + headline = "Flights halted at airports across US due to air traffic control problems" + blocks = [ + _story(headline, score=90 - i, article_id=100 + i, domain=domain, position=i) + for i, domain in enumerate(domains) + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 1 + assert kept[0]["article_id"] == 100 + assert stats["duplicates"] == 6 + assert len({record["duplicate_of"] for record in stats["duplicate_blocks"]}) == 1 + + +def test_rewrites_above_the_threshold_merge_and_below_do_not(): + original = "Flights halted at airports across US due to air traffic control communications problems" + u_s_variant = "Flights halted at airports across U.S. due to air traffic control communications problems" + other_story = "Flights halted at airports across US as a snowstorm closes runways" + + assert title_similarity(normalize_title(original), normalize_title(u_s_variant)) >= 0.85 + assert title_similarity(normalize_title(original), normalize_title(other_story)) < 0.85 + + kept, stats = dedupe_blocks( + [_story(original, article_id=1), _story(u_s_variant, article_id=2, score=80)] + ) + assert [block["article_id"] for block in kept] == [1] + assert stats["duplicates"] == 1 + assert stats["duplicate_blocks"][0]["similarity"] >= 0.85 + + kept, stats = dedupe_blocks( + [_story(original, article_id=1), _story(other_story, article_id=2, score=80)] + ) + assert len(kept) == 2 + assert stats["duplicates"] == 0 + + +def test_threshold_is_tunable(): + left = "Storm batters the coast with heavy rain and wind" + right = "Storm batters the coast with heavy rain, flooding and wind" + assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.75)[0]) == 1 + assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.99)[0]) == 2 + + +def test_different_categories_are_never_merged(): + headline = "Officials announce the election result" + blocks = [ + _story(headline, article_id=1, category="politics"), + _story(headline, article_id=2, score=80, category="military/conflict"), + _story(headline, article_id=3, score=70, category=None), + ] + kept, stats = dedupe_blocks(blocks) + # politics != military/conflict -> kept apart; NULL category may join politics. + assert [block["article_id"] for block in kept] == [1, 2] + assert stats["duplicates"] == 1 + assert stats["duplicate_blocks"][0]["article_id"] == 3 + + +def test_titles_disagreeing_on_a_number_stay_separate(): + blocks = [ + _story("Governor's Commutation Advisory Board – Part 1", article_id=1), + _story("Governor's Commutation Advisory Board – Part 2", article_id=2, score=80), + _story("Quake kills 12 in the northern province", article_id=3, score=70), + _story("Quake kills 21 in the northern province", article_id=4, score=60), + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 4 + assert stats["duplicates"] == 0 + + +def test_ties_keep_the_earliest_position(): + blocks = _blocks( + [ + (90, "a.com", "politics", 11, "Identical headline"), + (90, "b.com", "politics", 12, "Identical headline"), + ] + ) + kept, stats = dedupe_blocks(blocks) + assert [block["article_id"] for block in kept] == [11] + assert stats["duplicate_blocks"][0]["duplicate_of"] == 11 + + +def test_kept_blocks_stay_in_original_order(): + blocks = _blocks( + [ + (10, "a.com", "sport", 1, "Rangers beat the Chargers"), + (95, "b.com", "politics", 2, "Summit announced"), + (20, "c.com", "sport", 3, "Svitolina wins in straight sets"), + ] + ) + kept, _ = dedupe_blocks(blocks) + assert [block["article_id"] for block in kept] == [1, 2, 3] + + +# ── robustness ──────────────────────────────────────────────────────────── + +@pytest.mark.parametrize("blocks", [[], None]) +def test_empty_input_is_returned_untouched(blocks): + kept, stats = dedupe_blocks(blocks) + assert kept == [] + assert stats["input"] == 0 and stats["kept"] == 0 and stats["duplicates"] == 0 + + +def test_missing_and_null_titles_are_kept_and_never_merged(): + blocks = [ + {"position": 0, "score": 90, "text": "a"}, # no title key + {"position": 1, "score": 80, "title": None, "text": "b"}, + {"position": 2, "score": 70, "title": "", "text": "c"}, + {"position": 3, "score": 60, "title": " ", "text": "d"}, + {"position": 4, "score": 50, "title": "Real headline", "text": "e"}, + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 5 + assert stats["duplicates"] == 0 + + +def test_malformed_blocks_do_not_raise(): + kept, stats = dedupe_blocks( + [ + "not a dict", + {"position": 0, "score": "high", "title": "Headline", "text": "a"}, + {"position": 1, "score": None, "title": 42, "text": "b"}, + ] + ) + assert len(kept) == 2 + assert stats["input"] == 2 + + +def test_kill_switch_bypasses_everything(): + blocks = _blocks( + [ + (95, "a.com", "politics", 1, "Same headline"), + (94, "b.com", "politics", 2, "Same headline"), + ] + ) + kept, stats = dedupe_blocks(blocks, enabled=False) + assert [block["article_id"] for block in kept] == [1, 2] + assert stats["duplicates"] == 0 + assert stats["kept"] == 2 + + +def test_dedupe_config_reads_the_environment(monkeypatch): + monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) + monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) + assert summarizer.dedupe_config() == (True, DEFAULT_DEDUPE_SIMILARITY) + + monkeypatch.setenv("SUMMARY_DEDUPE", "0") + assert summarizer.dedupe_config()[0] is False + monkeypatch.setenv("SUMMARY_DEDUPE", "off") + assert summarizer.dedupe_config()[0] is False + + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "0.95") + assert summarizer.dedupe_config() == (False, 0.95) + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "nonsense") + assert summarizer.dedupe_config()[1] == DEFAULT_DEDUPE_SIMILARITY + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "7") + assert summarizer.dedupe_config()[1] == 1.0 + + +# ── replay of the measured run (summary id=6) ───────────────────────────── + +def test_replay_of_summary_6_collapses_21_to_9_and_selects_2(): + blocks = _blocks(OBSERVED_RUN) + assert len(blocks) == 21 + assert len({normalize_title(block["title"]) for block in blocks}) == 9 + + kept, stats = dedupe_blocks(blocks) + assert stats["input"] == 21 + assert stats["kept"] == 9 + assert stats["duplicates"] == 12 + assert len(kept) == 9 + + selected, fallback = select_graded(kept, min_score=60, top_n=12, fallback_top=3) + assert fallback is False + assert [block["score"] for block in selected] == [95, 75] + assert [block["article_id"] for block in selected] == [17263, 23748] + + # Every one of the 12 dropped copies points at one of the two survivors. + survivors = {record["duplicate_of"] for record in stats["duplicate_blocks"]} + assert survivors == {17263, 23748} + # 11 dropped copies still score above SUMMARY_MIN_SCORE; none is selected. + dropped_above = [ + record for record in stats["duplicate_blocks"] if record["score"] >= 60 + ] + assert len(dropped_above) == 11 + + +# ── wiring: one article_scores row per graded article ───────────────────── + +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 (77,) + 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): + pass + + def close(self): + pass + + +def _map_block(n: int, score: int) -> str: + return "\n".join( + [ + f"Article {n}:", + f"- Score: {score}", + "- Fact bullet", + "- Category: politics", + "- Importance: high", + ] + ) + + +def test_duplicates_are_persisted_unselected_with_duplicate_of(monkeypatch): + """Full summarize_news flow: 4 graded articles, 2 of them the same story.""" + summerizer_articles = [ + {"id": 1, "title": "Summit announced in the region", "content": "x" * 120, + "url": "https://a.com/1", "domain": "a.com"}, + {"id": 2, "title": "Summit announced in the region - KCCI", "content": "x" * 120, + "url": "https://b.com/2", "domain": "b.com"}, + {"id": 3, "title": "Tanker strikes a docked cruise ship", "content": "x" * 120, + "url": "https://c.com/3", "domain": "c.com"}, + {"id": 4, "title": "Rangers win in overtime", "content": "x" * 120, + "url": "https://d.com/4", "domain": "d.com"}, + ] + map_reply = "\n\n".join( + [_map_block(1, 95), _map_block(2, 92), _map_block(3, 55), _map_block(4, 5)] + ) + reduce_reply = json.dumps({"summary_en": "Brief.", "ticker": [], "map_items": []}) + db_log: list = [] + prompts: list[str] = [] + + def fake_chat(prompt, *, api_key, model, base_url, json_mode=False): + prompts.append(prompt) + return reduce_reply if json_mode else map_reply + + monkeypatch.setenv("NOUS_API_KEY", "test-key") + monkeypatch.setenv("SUMMARY_MODEL", "test-model") + monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) + monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) + monkeypatch.setattr(summarizer, "BATCH_SIZE", 10) + monkeypatch.setattr(summarizer, "call_llm", fake_chat) + monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: summerizer_articles) + monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False) + monkeypatch.setattr(summarizer, "ensure_tables", lambda: None) + monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _FakeConn(db_log)) + + summarizer.summarize_news() + + reduce_prompt = prompts[-1] + assert "Score: 95" in reduce_prompt + assert "Score: 92" not in reduce_prompt # wire copy never reaches reduce + + rows = [entry[2] for entry in db_log if entry[0] == "executemany"] + assert rows, db_log + by_article = {row[0]: row for row in rows[-1]} + assert sorted(by_article) == [1, 2, 3, 4] # one row per graded article + assert by_article[1][4] is True and by_article[1][6] is None + assert by_article[2][4] is False and by_article[2][6] == 1 # duplicate_of + assert by_article[3][4] is False and by_article[3][6] is None + assert by_article[4][4] is False and by_article[4][6] is None From c572f0ee608e6cc152d8f2962ff17eb6af23fd39 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 14 Nov 2026 00:30:04 -0500 Subject: [PATCH 06/21] fix(hud): hide vessel and FIRMS rows when those feeds are unset Read feeds.vessels.configured and feeds.fires.configured from /api/stats. A missing feeds object leaves both rows visible. WFIGS and trains stay. --- app/static/index.html | 18 +++++ tests/test_feed_rail.py | 152 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 170 insertions(+) create mode 100644 tests/test_feed_rail.py diff --git a/app/static/index.html b/app/static/index.html index acca754..956f4d5 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -1508,6 +1508,23 @@ function setLayerCount(id, value) { } } +function applyFeedConfig(s) { + // Hide only when /api/stats says the key is unset. Missing feeds (old image) + // leaves both rows visible. Never infer from a zero count. Never touch WFIGS or trains. + const feeds = (s && typeof s.feeds === 'object' && s.feeds) ? s.feeds : null; + setFeedRow('lp-vessels-on', feeds && feeds.vessels); + setFeedRow('lp-fires-on', feeds && feeds.fires); +} +function setFeedRow(id, flag) { + const el = document.getElementById(id); + const row = el && el.closest ? el.closest('.lp-layer') : null; + if (!row) return; + const hide = !!(flag && flag.configured === false); + row.hidden = hide; + // .lp-layer { display:flex } beats the UA [hidden] rule — inline display is what hides it. + row.style.display = hide ? 'none' : ''; +} + async function pollLayerStats() { if (statsPollDisabled) return; try { @@ -1516,6 +1533,7 @@ async function pollLayerStats() { if (!r.ok) return; const s = await r.json(); if (!s || typeof s !== 'object') return; + applyFeedConfig(s); statsRailActive = true; const skipIfOn = { fires: firesOn, diff --git a/tests/test_feed_rail.py b/tests/test_feed_rail.py new file mode 100644 index 0000000..cde7d53 --- /dev/null +++ b/tests/test_feed_rail.py @@ -0,0 +1,152 @@ +"""Layer rail hides Vessels and FIRMS only when /api/stats says the key is unset.""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def _between(start: str, end: str) -> str: + return HTML.split(start, 1)[1].split(end, 1)[0] + + +def _feed_fns() -> str: + return _between("function applyFeedConfig", "async function pollLayerStats") + + +def _layer_chunk(elem_id: str) -> str: + idx = HTML.index(f'id="{elem_id}"') + start = HTML.rfind(' +
+
+ + 0 +
+
@@ -1121,6 +1144,7 @@
CAMS —
BLIPS —
NEWS —
+
ARTICLES —