diff --git a/app/main.py b/app/main.py index c2f4765..2d7a3f6 100644 --- a/app/main.py +++ b/app/main.py @@ -1293,12 +1293,7 @@ async def list_news( ): """Most recent scraped news articles (newest first).""" async with async_session() as session: - stmt = select(articles).where( - or_( - articles.c.timestamp.is_(None), - articles.c.timestamp <= func.now(), - ) - ).order_by( + stmt = select(articles).order_by( articles.c.timestamp.desc().nullslast() ) if domain: diff --git a/docs/news.md b/docs/news.md index ac25c36..d64b31d 100644 --- a/docs/news.md +++ b/docs/news.md @@ -43,10 +43,7 @@ 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`). 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. + (`ON CONFLICT (url) DO NOTHING`). 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 2629372..68cad97 100644 --- a/news/scraper/newsScraper/pipelines.py +++ b/news/scraper/newsScraper/pipelines.py @@ -3,49 +3,10 @@ # 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): @@ -53,8 +14,6 @@ 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): @@ -95,12 +54,6 @@ 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) @@ -129,11 +82,6 @@ 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 cf7ab77..e94b0e3 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, timedelta, timezone +from datetime import datetime, timezone import asyncpg import httpx @@ -157,26 +157,6 @@ 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 ac335c2..b2b3817 100644 --- a/tests/test_news_scraper.py +++ b/tests/test_news_scraper.py @@ -2,12 +2,9 @@ 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: @@ -43,93 +40,3 @@ 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 -