fix(summarizer): ignore future-dated rows; require a score floor for the fallback #54
7 changed files with 311 additions and 23 deletions
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.
commit
57c0444a69
|
|
@ -100,11 +100,13 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1
|
||||||
NEWS_BATCH_SIZE=50
|
NEWS_BATCH_SIZE=50
|
||||||
# Map-phase grading: the map model scores each article 0-100, and only blocks
|
# 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).
|
# with score >= SUMMARY_MIN_SCORE reach the reduce brief (best first).
|
||||||
# If nothing clears the bar, the top SUMMARY_FALLBACK_TOP blocks are used
|
# If nothing clears the bar, up to SUMMARY_FALLBACK_TOP blocks scoring at least
|
||||||
# (0 = honour the threshold and pass an empty DATA section instead).
|
# 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_MIN_SCORE=60
|
||||||
SUMMARY_TOP_N=12
|
SUMMARY_TOP_N=12
|
||||||
SUMMARY_FALLBACK_TOP=3
|
SUMMARY_FALLBACK_TOP=3
|
||||||
|
SUMMARY_FALLBACK_MIN_SCORE=40
|
||||||
SUMMARY_WINDOW_MINUTES=15
|
SUMMARY_WINDOW_MINUTES=15
|
||||||
# Futures/markets coupling from the upstream pipeline is OFF by default
|
# Futures/markets coupling from the upstream pipeline is OFF by default
|
||||||
# (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable.
|
# (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable.
|
||||||
|
|
|
||||||
11
docs/news.md
11
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
|
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
|
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
|
`>= 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
|
at `SUMMARY_TOP_N` (default 12). If nothing clears the bar, up to
|
||||||
`SUMMARY_FALLBACK_TOP` blocks (default 3) are used so the HUD is not blank;
|
`SUMMARY_FALLBACK_TOP` blocks (default 3) scoring at least
|
||||||
`SUMMARY_FALLBACK_TOP=0` passes an empty DATA section instead. The reduce prompt
|
`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
|
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
|
promotes an item above its score. Every graded article is persisted to
|
||||||
`article_scores` (score, category, selected, model, summary_id) so the operator
|
`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_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_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_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_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). |
|
| `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). |
|
||||||
| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. |
|
| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. |
|
||||||
|
|
|
||||||
|
|
@ -210,13 +210,20 @@ def parse_map_scores(
|
||||||
|
|
||||||
|
|
||||||
def select_graded(
|
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]:
|
) -> tuple[list[dict], bool]:
|
||||||
"""Rank blocks best-first and return the ones the reduce phase should see.
|
"""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
|
Keeps ``score >= min_score`` capped at ``top_n`` (stable on ties: original
|
||||||
order). When nothing clears the bar, returns the top ``fallback_top`` blocks
|
order). When nothing clears the bar, returns up to ``fallback_top`` blocks
|
||||||
and True; ``fallback_top == 0`` yields an empty selection.
|
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))
|
ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0))
|
||||||
limit = max(0, int(top_n))
|
limit = max(0, int(top_n))
|
||||||
|
|
@ -226,7 +233,11 @@ def select_graded(
|
||||||
fallback_limit = max(0, int(fallback_top))
|
fallback_limit = max(0, int(fallback_top))
|
||||||
if fallback_limit <= 0:
|
if fallback_limit <= 0:
|
||||||
return [], False
|
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:
|
def join_blocks(blocks: list[dict]) -> str:
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,7 @@ BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
||||||
DEFAULT_SUMMARY_MIN_SCORE = 60
|
DEFAULT_SUMMARY_MIN_SCORE = 60
|
||||||
DEFAULT_SUMMARY_TOP_N = 12
|
DEFAULT_SUMMARY_TOP_N = 12
|
||||||
DEFAULT_SUMMARY_FALLBACK_TOP = 3
|
DEFAULT_SUMMARY_FALLBACK_TOP = 3
|
||||||
|
DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40
|
||||||
|
|
||||||
|
|
||||||
def _env_int(name: str, default: int) -> int:
|
def _env_int(name: str, default: int) -> int:
|
||||||
|
|
@ -67,12 +68,15 @@ def _env_int(name: str, default: int) -> int:
|
||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
def selection_config() -> tuple[int, int, int]:
|
def selection_config() -> tuple[int, int, int, int]:
|
||||||
"""(min_score, top_n, fallback_top) from env, read per run."""
|
"""(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)))
|
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))
|
top_n = max(0, _env_int("SUMMARY_TOP_N", DEFAULT_SUMMARY_TOP_N))
|
||||||
fallback_top = max(0, _env_int("SUMMARY_FALLBACK_TOP", DEFAULT_SUMMARY_FALLBACK_TOP))
|
fallback_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:
|
def _summary_window_minutes() -> int:
|
||||||
|
|
@ -389,12 +393,18 @@ def ensure_tables() -> None:
|
||||||
|
|
||||||
|
|
||||||
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
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()
|
mins = window_minutes if window_minutes is not None else effective_window_minutes()
|
||||||
query = """
|
query = """
|
||||||
SELECT id, title, content, url, domain
|
SELECT id, title, content, url, domain
|
||||||
FROM articles
|
FROM articles
|
||||||
WHERE timestamp > NOW() - make_interval(mins => %s)
|
WHERE timestamp > NOW() - make_interval(mins => %s)
|
||||||
|
AND timestamp <= NOW()
|
||||||
AND content IS NOT NULL AND length(content) > 100
|
AND content IS NOT NULL AND length(content) > 100
|
||||||
ORDER BY timestamp DESC;
|
ORDER BY timestamp DESC;
|
||||||
"""
|
"""
|
||||||
|
|
@ -629,12 +639,12 @@ def summarize_news() -> None:
|
||||||
logger.info("No new articles found in the last %s min.", window)
|
logger.info("No new articles found in the last %s min.", window)
|
||||||
return
|
return
|
||||||
|
|
||||||
min_score, top_n, fallback_top = selection_config()
|
min_score, top_n, fallback_top, fallback_min_score = selection_config()
|
||||||
logger.info(
|
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)...",
|
"min_score=%d, top_n=%d, fallback_top=%d, fallback_min_score=%d)...",
|
||||||
len(articles), model, BATCH_SIZE, recap, window,
|
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] = []
|
graded: list[dict] = []
|
||||||
|
|
@ -669,7 +679,11 @@ def summarize_news() -> None:
|
||||||
return
|
return
|
||||||
|
|
||||||
selected, used_fallback = select_graded(
|
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}
|
selected_positions = {block["position"] for block in selected}
|
||||||
for block in graded:
|
for block in graded:
|
||||||
|
|
@ -677,8 +691,9 @@ def summarize_news() -> None:
|
||||||
if used_fallback:
|
if used_fallback:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d "
|
"No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d "
|
||||||
"(max score %d)",
|
"with score >= %d (max score %d)",
|
||||||
min_score, len(selected), max(b["score"] for b in graded),
|
min_score, len(selected), fallback_min_score,
|
||||||
|
max(b["score"] for b in graded),
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"selected %d/%d graded articles for reduce (scores=%s)",
|
"selected %d/%d graded articles for reduce (scores=%s)",
|
||||||
|
|
@ -688,8 +703,9 @@ def summarize_news() -> None:
|
||||||
final_input = join_blocks(selected)
|
final_input = join_blocks(selected)
|
||||||
if not final_input.strip():
|
if not final_input.strip():
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Selection is empty (min_score=%d, fallback_top=%d) — reduce gets empty DATA.",
|
"Selection is empty (min_score=%d, fallback_top=%d, "
|
||||||
min_score, fallback_top,
|
"fallback_min_score=%d) — reduce gets empty DATA.",
|
||||||
|
min_score, fallback_top, fallback_min_score,
|
||||||
)
|
)
|
||||||
|
|
||||||
master_raw = call_llm(
|
master_raw = call_llm(
|
||||||
|
|
|
||||||
|
|
@ -152,6 +152,63 @@ def test_nothing_clears_the_bar_uses_fallback_top():
|
||||||
assert fallback is True
|
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():
|
def test_fallback_top_zero_yields_empty_selection():
|
||||||
blocks = _scored([40, 12, 55])
|
blocks = _scored([40, 12, 55])
|
||||||
selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=0)
|
selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=0)
|
||||||
|
|
|
||||||
|
|
@ -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))
|
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):
|
def test_score_insert_failure_does_not_abort_the_run(harness, monkeypatch):
|
||||||
calls, db_log = harness
|
calls, db_log = harness
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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 (
|
from summarizer import (
|
||||||
build_map_prompt,
|
build_map_prompt,
|
||||||
build_master_prompt,
|
build_master_prompt,
|
||||||
effective_window_minutes,
|
effective_window_minutes,
|
||||||
|
get_recent_news,
|
||||||
is_recap_run,
|
is_recap_run,
|
||||||
|
selection_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -43,3 +52,164 @@ def test_build_master_prompt_recap_uses_daily_template():
|
||||||
assert "partial facts" in prompt
|
assert "partial facts" in prompt
|
||||||
assert "daily recap" in prompt.lower()
|
assert "daily recap" in prompt.lower()
|
||||||
assert "24" in prompt
|
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