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.
This commit is contained in:
backend 2026-11-13 21:41:44 -05:00
commit c42d375d6c
5 changed files with 176 additions and 3 deletions

View file

@ -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")

View file

@ -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