An open source, non-profit web search engine
Key the Redis daily and hourly counters off aware UTC
claude[bot]740ddb36438e
diff --git a/docs/plans/issue-371-enable-dtz-rule.md b/docs/plans/issue-371-enable-dtz-rule.mdindex 8881c2c..47cb887 100644--- a/docs/plans/issue-371-enable-dtz-rule.md+++ b/docs/plans/issue-371-enable-dtz-rule.md@@ -110,7 +110,7 @@ bloom filter file.- No `replace(tzinfo=None)` remains in `mwmbl/crawler/` or `mwmbl/indexer/`- `ruff check --select DTZ` count is 61 → 41-## PR 3: Key the Redis daily and hourly counters off aware UTC+## PR 3: Key the Redis daily and hourly counters off aware UTC (Done)**Estimated added lines:** ~130 (27 sites across 5 files, plus one helper and its test)**Files:** mwmbl/utils.py, mwmbl/crawler/stats.py, mwmbl/count_urls.py,mwmbl/admin_views.py, mwmbl/crawler/app.py, test/test_stats_blacklisted_removed.pydiff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.pyindex ca8db66..bb92f17 100644--- a/mwmbl/admin_views.py+++ b/mwmbl/admin_views.py@@ -13,7 +13,7 @@ SRANDMEMBER so looking at it cannot consume it."""import os-from datetime import datetime, timedelta+from datetime import timedeltafrom logging import getLoggerfrom background_task.models import CompletedTask, Task@@ -32,6 +32,7 @@ from mwmbl.indexer.blacklist_snapshot import (get_snapshot_blacklist,)from mwmbl.indexer.purge_queue import MAX_QUEUE_SIZE, PURGE_QUEUE_KEY, peek_purge_queue+from mwmbl.utils import utc_todaylogger = getLogger(__name__)@@ -99,7 +100,7 @@ def _removed_counts(days: int) -> list[dict]:broken loop - see StatsManager.record_blacklisted_removed."""client = purge_queue.get_redis()- today = datetime.utcnow().date()+ today = utc_today()dates = [today - timedelta(days=i) for i in range(days)]counts = client.mget([BLACKLISTED_REMOVED_COUNT_KEY.format(date=date) for date in dates])return [{"date": date, "count": int(count) if count else 0} for date, count in zip(dates, counts)]diff --git a/mwmbl/count_urls.py b/mwmbl/count_urls.pyindex 12fe7df..0e2befe 100644--- a/mwmbl/count_urls.py+++ b/mwmbl/count_urls.py@@ -1,6 +1,6 @@import osfrom collections import Counter-from datetime import date, datetime, timedelta+from datetime import datetime, timedelta, timezonefrom logging import getLoggerfrom pathlib import Pathfrom random import Random@@ -11,7 +11,7 @@ from pydistinct.stats_estimators import smoothed_jackknife_estimatorfrom redis import Redisfrom mwmbl.tinysearchengine.indexer import Document, PageError, TinyIndex-from mwmbl.utils import parse_url+from mwmbl.utils import parse_url, utc_todayINDEX_RESULT_COUNT_KEY = "index-result-count-{date}"INDEX_DOMAIN_COUNT_KEY = "index-domain-count-{date}"@@ -33,9 +33,9 @@ def get_redis():def count_urls_continuously():while True:- start_time = datetime.utcnow()+ start_time = datetime.now(timezone.utc)count_urls()- end_time = datetime.utcnow()+ end_time = datetime.now(timezone.utc)total_time = end_time - start_timetime_remaining = 60 * 60 * 24 - total_time.total_seconds()logger.info(f"Counting took {total_time}. Sleeping for {timedelta(seconds=time_remaining)}.")@@ -43,7 +43,7 @@ def count_urls_continuously():def count_urls():- start_time = datetime.utcnow()+ start_time = datetime.now(timezone.utc)index_path = Path(settings.DATA_PATH) / settings.INDEX_NAMEwith TinyIndex(item_factory=Document, index_path=index_path) as index:@@ -83,12 +83,12 @@ def count_urls():redis = get_redis()- today = date.today()+ today = utc_today()_set_count(INDEX_URL_COUNT_KEY, redis, today, int(url_count_estimate))_set_count(INDEX_DOMAIN_COUNT_KEY, redis, today, int(domain_count_estimate))_set_count(INDEX_RESULT_COUNT_KEY, redis, today, num_results_estimate)- end_time = datetime.utcnow()+ end_time = datetime.now(timezone.utc)logger.info(f"Counting took {end_time - start_time}.")@@ -100,7 +100,7 @@ def _set_count(key, redis, today, count):def get_counts() -> dict[str, dict[str, int]]:redis = get_redis()- today = date.today()+ today = utc_today()urls_in_index_daily = {}domains_in_index_daily = {}@@ -122,7 +122,7 @@ def get_counts() -> dict[str, dict[str, int]]:def get_domain_result_count(domain: str) -> int:redis = get_redis()- today = date.today()+ today = utc_today()count = redis.zscore(INDEX_DOMAIN_RESULT_COUNT_KEY.format(date=today), domain)return 0 if count is None else int(count)diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex c00695d..a4b8cab 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -2,7 +2,7 @@ import gzipimport hashlibimport jsonimport os-from datetime import date, datetime, timezone+from datetime import datetime, timezonefrom logging import getLoggerfrom queue import Emptyfrom typing import Union@@ -46,6 +46,7 @@ from mwmbl.settings import (VERSION,)from mwmbl.tinysearchengine.indexer import Document+from mwmbl.utils import utc_todaystats_manager = StatsManager(Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)@@ -457,7 +458,7 @@ def get_batches_for_date(date_str):batches = get_batches_for_prefix(prefix)result = {"batch_urls": [f"{PUBLIC_URL_PREFIX}{batch}" for batch in sorted(batches)]}- if date_str != str(date.today()):+ if date_str != str(utc_today()):# Don't cache data from today since it may changedata = gzip.compress(json.dumps(result).encode("utf8"))upload(data, cache_filename)diff --git a/mwmbl/crawler/stats.py b/mwmbl/crawler/stats.pyindex 8dd6df7..3800210 100644--- a/mwmbl/crawler/stats.py+++ b/mwmbl/crawler/stats.py@@ -1,5 +1,5 @@import gzip-from datetime import datetime, timedelta+from datetime import date, datetime, timedelta, timezonefrom glob import globfrom itertools import islicefrom logging import getLogger@@ -13,6 +13,7 @@ from mwmbl.count_urls import get_counts, get_domain_result_countfrom mwmbl.crawler.batch import HashedBatch, Resultsfrom mwmbl.crawler.urls import URLDatabasefrom mwmbl.indexer.update_urls import get_datetime_from_timestamp+from mwmbl.utils import utc_todaylogger = getLogger(__name__)@@ -34,6 +35,17 @@ SHORT_EXPIRE_SECONDS = 60 * 60 * 24LONG_EXPIRE_SECONDS = 60 * 60 * 24 * 30+def hour_count_key(date_time: datetime) -> str:+ """Key naming the hour a crawl happened in, e.g. ``url-count-hour-2026-09-08 13:00:00``.++ Formatted rather than built from a truncated datetime so that the key does not depend+ on whether ``date_time`` is aware: ``str()`` of an aware datetime carries a ``+00:00``+ suffix, which would split the writer in :meth:`StatsManager.record_batch` from the+ reader in :meth:`StatsManager.get_stats` and zero the hourly chart.+ """+ return URL_HOUR_COUNT_KEY.format(hour=date_time.strftime("%Y-%m-%d %H:00:00"))++class DomainStats(BaseModel):domain_name: strnum_crawled: int@@ -92,8 +104,7 @@ class StatsManager:self.redis.expire(url_count_key, LONG_EXPIRE_SECONDS)print("Date time", date_time)- hour = datetime(date_time.year, date_time.month, date_time.day, date_time.hour)- hour_key = URL_HOUR_COUNT_KEY.format(hour=hour)+ hour_key = hour_count_key(date_time)self.redis.incrby(hour_key, num_crawled_urls)self.redis.expire(hour_key, SHORT_EXPIRE_SECONDS)@@ -105,7 +116,7 @@ class StatsManager:self.redis.zincrby(user_count_key, num_crawled_urls, hashed_batch.user_id_hash)self.redis.expire(user_count_key, SHORT_EXPIRE_SECONDS)- start_time = datetime.utcnow()+ start_time = datetime.now(timezone.utc)host_key = HOST_COUNT_KEY.format(date=date)host_all_key = HOST_COUNT_ALL_KEY.format(date=date)pipeline = self.redis.pipeline()@@ -135,13 +146,13 @@ class StatsManager:pipeline.zincrby(HOST_COUNT_LINK_NEW_KEY.format(date=date), 1, link_host)pipeline.execute()- total_time = (datetime.utcnow() - start_time).total_seconds()+ total_time = (datetime.now(timezone.utc) - start_time).total_seconds()logger.info(f"Stored info for {len(hashed_batch.items)} items in Redis in {total_time:.2f} seconds")self.redis.expire(host_key, SHORT_EXPIRE_SECONDS)self.redis.expire(host_all_key, SHORT_EXPIRE_SECONDS)def get_stats(self) -> MwmblStats:- date_time = datetime.utcnow()+ date_time = datetime.now(timezone.utc)date = date_time.date()urls_crawled_daily = {}@@ -188,8 +199,7 @@ class StatsManager:hour_counts = []for i in range(date_time.hour + 1):- hour = datetime(date_time.year, date_time.month, date_time.day, i)- hour_key = URL_HOUR_COUNT_KEY.format(hour=hour)+ hour_key = hour_count_key(date_time.replace(hour=i))hour_count = self.redis.get(hour_key)if hour_count is None:hour_count = 0@@ -223,14 +233,14 @@ class StatsManager:)def get_domain_stats(self) -> list[DomainStats]:- date_time = datetime.utcnow()- host_all_key = HOST_COUNT_ALL_KEY.format(date=date_time.date())+ today = utc_today()+ host_all_key = HOST_COUNT_ALL_KEY.format(date=today)host_counts_all = self.redis.zrevrange(host_all_key, 0, 1000, withscores=True)all_domain_stats = []for host, count in host_counts_all:- num_successful = self.redis.zscore(HOST_COUNT_KEY.format(date=date_time.date()), host)- num_links = self.redis.zscore(HOST_COUNT_LINK_KEY.format(date=date_time.date()), host)- num_links_new = self.redis.zscore(HOST_COUNT_LINK_NEW_KEY.format(date=date_time.date()), host)+ num_successful = self.redis.zscore(HOST_COUNT_KEY.format(date=today), host)+ num_links = self.redis.zscore(HOST_COUNT_LINK_KEY.format(date=today), host)+ num_links_new = self.redis.zscore(HOST_COUNT_LINK_NEW_KEY.format(date=today), host)num_index_results = get_domain_result_count(host)domain_stats = DomainStats(domain_name=host,@@ -244,11 +254,11 @@ class StatsManager:return all_domain_statsdef get_stats_for_domain(self, host: str) -> DomainStats:- date_time = datetime.utcnow()- num_crawled = self.redis.zscore(HOST_COUNT_ALL_KEY.format(date=date_time.date()), host)- num_successful = self.redis.zscore(HOST_COUNT_KEY.format(date=date_time.date()), host)- num_links = self.redis.zscore(HOST_COUNT_LINK_KEY.format(date=date_time.date()), host)- num_links_new = self.redis.zscore(HOST_COUNT_LINK_NEW_KEY.format(date=date_time.date()), host)+ today = utc_today()+ num_crawled = self.redis.zscore(HOST_COUNT_ALL_KEY.format(date=today), host)+ num_successful = self.redis.zscore(HOST_COUNT_KEY.format(date=today), host)+ num_links = self.redis.zscore(HOST_COUNT_LINK_KEY.format(date=today), host)+ num_links_new = self.redis.zscore(HOST_COUNT_LINK_NEW_KEY.format(date=today), host)num_index_results = get_domain_result_count(host)domain_stats = DomainStats(domain_name=host,@@ -262,11 +272,11 @@ class StatsManager:def record_results(self, results: Results, username: str) -> None:num_results = len(results.results)- result_count_key = RESULTS_COUNT_KEY.format(date=datetime.utcnow().date())+ result_count_key = RESULTS_COUNT_KEY.format(date=utc_today())self.redis.incrby(result_count_key, num_results)self.redis.expire(result_count_key, LONG_EXPIRE_SECONDS)- user_result_count_key = USER_RESULTS_COUNT_KEY.format(date=datetime.utcnow().date())+ user_result_count_key = USER_RESULTS_COUNT_KEY.format(date=utc_today())self.redis.zincrby(user_result_count_key, num_results, username)self.redis.expire(user_result_count_key, SHORT_EXPIRE_SECONDS)@@ -278,20 +288,18 @@ class StatsManager:a count that stays at zero while queries are being filtered means the loop isbroken."""- blacklisted_removed_count_key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())+ blacklisted_removed_count_key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=utc_today())self.redis.incrby(blacklisted_removed_count_key, num_results)self.redis.expire(blacklisted_removed_count_key, LONG_EXPIRE_SECONDS)def record_dataset(self, hashed_dataset) -> None:"""Record dataset statistics from a dataset submission."""- from datetime import datetime-# Parse the date from the datasettry:- dataset_date = datetime.strptime(hashed_dataset.date, "%Y-%m-%d").date()+ dataset_date = date.fromisoformat(hashed_dataset.date)except ValueError:# If date parsing fails, use current date- dataset_date = datetime.utcnow().date()+ dataset_date = utc_today()# Count queriesnum_queries = len(hashed_dataset.queryDataset)@@ -322,7 +330,7 @@ if __name__ == "__main__":redis = Redis(host="localhost", port=6379, decode_responses=True)stats = StatsManager(redis)batches = get_test_batches()- start = datetime.now()+ start = datetime.now(timezone.utc)processed = 0import logging@@ -332,7 +340,7 @@ if __name__ == "__main__":continuestats.record_batch(batch)processed += 1- total_time = (datetime.now() - start).total_seconds()+ total_time = (datetime.now(timezone.utc) - start).total_seconds()print("Processed", processed)print("Total time", total_time)print("Time per batch", total_time / processed)diff --git a/mwmbl/utils.py b/mwmbl/utils.pyindex 43f0ecb..10f3179 100644--- a/mwmbl/utils.py+++ b/mwmbl/utils.py@@ -1,6 +1,6 @@import refrom dataclasses import dataclass-from datetime import timedelta+from datetime import date, datetime, timedelta, timezonefrom typing import Optional, Sequencefrom django.conf import settings@@ -13,6 +13,16 @@ from mwmbl.tinysearchengine.indexer import Document, TinyIndexDOMAIN_REGEX = re.compile(r".*://([^/]*)")+def utc_today() -> date:+ """Today in UTC, whatever the server's local timezone is.++ Daily Redis counters are keyed by this date, and the crawler's S3 batch prefixes are+ UTC, so a local date would name a different day's key for hours either side of+ midnight.+ """+ return datetime.now(timezone.utc).date()++def batch(items: Sequence, batch_size):"""Adapted from https://stackoverflow.com/a/8290508diff --git a/test/test_stats_blacklisted_removed.py b/test/test_stats_blacklisted_removed.pyindex c489db2..0cf4ca5 100644--- a/test/test_stats_blacklisted_removed.py+++ b/test/test_stats_blacklisted_removed.py@@ -6,12 +6,12 @@ ever removes them, so a broken purge loop is invisible from the search results aThis counter is the only signal that the removals are actually happening."""-from datetime import datetimefrom unittest.mock import patchimport fakeredisfrom mwmbl.crawler.stats import BLACKLISTED_REMOVED_COUNT_KEY, LONG_EXPIRE_SECONDS, StatsManager+from mwmbl.utils import utc_todayNO_INDEX_COUNTS = {"urls_in_index_daily": {},@@ -30,7 +30,7 @@ def test_recorded_removals_appear_in_the_stats_for_today():with patch("mwmbl.crawler.stats.get_counts", return_value=NO_INDEX_COUNTS):stats = stats_manager.get_stats()- today = str(datetime.utcnow().date())+ today = str(utc_today())assert stats.blacklisted_results_removed_daily[today] == 7@@ -49,7 +49,7 @@ def test_the_daily_count_expires_so_it_cannot_grow_without_bound():redis = fakeredis.FakeRedis(decode_responses=True)StatsManager(redis).record_blacklisted_removed(1)- key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())+ key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=utc_today())assert 0 < redis.ttl(key) <= LONG_EXPIRE_SECONDS@@ -71,7 +71,7 @@ def test_the_purge_task_records_what_it_removed():purge_blacklisted_from_queue.now()- key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())+ key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=utc_today())assert redis.get(key) == "5"@@ -86,4 +86,4 @@ def test_the_purge_task_records_nothing_when_the_queue_is_empty():purge_blacklisted_from_queue.now()- assert redis.get(BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())) is None+ assert redis.get(BLACKLISTED_REMOVED_COUNT_KEY.format(date=utc_today())) is Nonediff --git a/test/test_stats_hourly_counts.py b/test/test_stats_hourly_counts.pynew file mode 100644index 0000000..8bb1ff4--- /dev/null+++ b/test/test_stats_hourly_counts.py@@ -0,0 +1,59 @@+"""+Tests for the hourly crawl counter behind the "URLs crawled" chart.++The key is a formatted datetime, so it is the one daily counter whose Redis key changes+if the datetime it is built from becomes timezone-aware: `str()` of an aware datetime+carries a `+00:00` suffix. Writer and reader are in different methods, so getting this+wrong on one side alone empties the chart silently.+"""++from datetime import datetime, timezone+from unittest.mock import patch++import fakeredis++from mwmbl.crawler.batch import HashedBatch, Item, ItemContent+from mwmbl.crawler.stats import URL_HOUR_COUNT_KEY, StatsManager, hour_count_key++NO_INDEX_COUNTS = {+ "urls_in_index_daily": {},+ "domains_in_index_daily": {},+ "results_in_index_daily": {},+}+++def make_batch(crawled_at: datetime) -> HashedBatch:+ content = ItemContent(title="Example", extract="An example page", links=[], extra_links=[])+ item = Item(url="https://example.com/", status=200, timestamp=crawled_at.timestamp(), content=content)+ return HashedBatch(user_id_hash="a" * 64, timestamp=crawled_at.timestamp(), items=[item])+++def test_the_hour_key_has_no_timezone_offset_in_it():+ aware = datetime(2026, 9, 8, 13, 45, tzinfo=timezone.utc)+ assert hour_count_key(aware) == "url-count-hour-2026-09-08 13:00:00"+++def test_a_recorded_batch_is_counted_against_the_utc_hour_it_was_crawled_in():+ redis = fakeredis.FakeRedis(decode_responses=True)+ crawled_at = datetime(2026, 9, 8, 13, 45, tzinfo=timezone.utc)++ with patch("mwmbl.crawler.stats.URLDatabase"):+ StatsManager(redis).record_batch(make_batch(crawled_at))++ assert redis.get(URL_HOUR_COUNT_KEY.format(hour="2026-09-08 13:00:00")) == "1"+++def test_the_stats_read_back_the_hour_key_the_batch_wrote():+ """The chart is built by get_stats reading keys record_batch wrote, so the two have to+ agree on the format - not just each be self-consistent."""+ redis = fakeredis.FakeRedis(decode_responses=True)+ now = datetime.now(timezone.utc)++ with patch("mwmbl.crawler.stats.URLDatabase"):+ stats_manager = StatsManager(redis)+ stats_manager.record_batch(make_batch(now))++ with patch("mwmbl.crawler.stats.get_counts", return_value=NO_INDEX_COUNTS):+ stats = stats_manager.get_stats()++ assert stats.urls_crawled_hourly[now.hour] == 1