fix(summarizer): ignore future-dated rows; require a score floor for the fallback
Two leaks let low-value items reach the operator brief: - get_recent_news() only bounded the window from below, so event listings dated days ahead (wiseye.org, +3d/+6d) were re-fetched, re-graded and re-billed every interval for a week. The window is now (now - N, now]; NULL timestamps stay excluded as before. - select_graded() returned ordered[:fallback_top] with no floor, so a 15/100 event listing entered the brief as 'low'. New SUMMARY_FALLBACK_MIN_SCORE (default 40, clamped 0-100) filters the fallback set; when nothing clears it the reduce phase gets empty DATA and writes the empty-brief response. The fallback WARNING now logs the floor. Docs: .env.example and docs/news.md document the new knob and window.
This commit is contained in:
parent
2c41737d42
commit
57c0444a69
7 changed files with 311 additions and 23 deletions
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in a new issue