An open source, non-profit web search engine
Count keyed Combined Search only below the limit, and fix the counter scans
Claude04d44a08c16d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4c74f26..b707647 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -50,6 +50,15 @@ jobs:--health-retries 5ports:- 5432:5432+ redis:+ image: redis:7+ options: >-+ --health-cmd "redis-cli ping"+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ ports:+ - 6379:6379steps:#----------------------------------------------@@ -110,5 +119,6 @@ jobs:env:DATABASE_URL: postgres://postgres:postgres@localhost:5432/test_mwmblDJANGO_SETTINGS_MODULE: mwmbl.settings_test+ TEST_REDIS_URL: redis://localhost:6379/15run: |uv run pytestdiff --git a/.github/workflows/claude-issues.yml b/.github/workflows/claude-issues.ymlindex 24fcb10..f778ad1 100644--- a/.github/workflows/claude-issues.yml+++ b/.github/workflows/claude-issues.yml@@ -190,6 +190,15 @@ jobs:--health-retries 5ports:- 5432:5432+ redis:+ image: redis:7+ options: >-+ --health-cmd "redis-cli ping"+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ ports:+ - 6379:6379env:ISSUE_NUMBER: ${{ matrix.item.issue }}@@ -216,6 +225,7 @@ jobs:echo "CLAUDE_RUN_LOG=$RUNNER_TEMP/claude-runs.jsonl"echo "DATABASE_URL=postgres://postgres:postgres@localhost:5432/test_mwmbl"echo "DJANGO_SETTINGS_MODULE=mwmbl.settings_test"+ echo "TEST_REDIS_URL=redis://localhost:6379/15"} >>"$GITHUB_ENV"# Full history: the run diffs the branch against main and pushes it.#diff --git a/AGENTS.md b/AGENTS.mdindex 77ba17e..be9dbbf 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -19,6 +19,9 @@ uv run manage.py <command> --settings=mwmbl.settings_dev`make test` and `make migrate` need `DATABASE_URL` in the environment, for example`DATABASE_URL="postgres://user@/mwmbl_test"`. Tests use `mwmbl.settings_test`.+The tests also need a running Redis: the quota counters' Lua scripts and key scans are+tested against a real one (the `redis_cache` fixture), in the database `TEST_REDIS_URL`+names, which the tests flush. `make test` defaults it to `redis://127.0.0.1:6379/15`.`make check` and `make test` are the two gates. Both must pass before you open a pullrequest, and `.pre-commit-config.yaml` runs the first of them on every commit.diff --git a/Makefile b/Makefileindex 3d1c9d9..2a175b4 100644--- a/Makefile+++ b/Makefile@@ -27,6 +27,8 @@# These have no defaults — you must set them in your environment or on the command line.DATABASE_URL ?=REDIS_URL ?= redis://127.0.0.1:6379+# A Redis database the tests flush, so keep it apart from REDIS_URL's.+TEST_REDIS_URL ?= redis://127.0.0.1:6379/15DJANGO_SETTINGS_MODULE ?= mwmbl.settings_dev@@ -80,11 +82,11 @@ migrate:uv run python manage.py migrate --settings=$(DJANGO_SETTINGS_MODULE)test:- DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" \+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" \uv run pytest $(PYTEST_ARGS)test-file:- DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" \+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" \uv run pytest $(FILE) -v $(PYTEST_ARGS)run:diff --git a/mwmbl/quota.py b/mwmbl/quota.pyindex f9dde07..aad4fe0 100644--- a/mwmbl/quota.py+++ b/mwmbl/quota.py@@ -2,14 +2,16 @@Quota and rate-limit helpers for the search API.All counters use the Django cache interface (django.core.cache.cache) so the-backend can be swapped without changing this code. The only Redis-specific-call is get_all_monthly_keys(), which uses SCAN via django-redis and is only-called by the background flush/reset jobs.+backend can be swapped without changing this code. The exceptions need+django-redis: the key scans, which use SCAN and are only called by background+jobs, and increment_monthly_combined_search_api_if_below(), which runs a Lua+script so that the check and the increment are one atomic step."""from datetime import datetime, timezonefrom django.core.cache import cache+from django_redis import get_redis_connectionRATE_LIMIT = 5 # maximum requests per second (all tiers)MONTHLY_TTL = 60 * 60 * 24 * 35 # 35 days in seconds@@ -156,23 +158,33 @@ def get_monthly_combined_search_api_count(user_id: int) -> int:return cache.get(_combined_search_api_monthly_key(user_id), default=0)-def increment_monthly_combined_search_api(user_id: int) -> int:- """Increment the monthly keyed combined-search counter and return the new value."""- key = _combined_search_api_monthly_key(user_id)- if cache.add(key, 1, timeout=MONTHLY_TTL):- return 1- return cache.incr(key)+# Count one request only if the counter is below the limit, in a single Redis step. An+# increment-then-refund would leave the counter one over the limit between the two steps,+# and an hourly sync reading it then would store, and later bill, a request that was refused.+_INCREMENT_IF_BELOW_LIMIT = """+local count = tonumber(redis.call('GET', KEYS[1]) or '0')+if count >= tonumber(ARGV[1]) then+ return -1+end+count = redis.call('INCR', KEYS[1])+if count == 1 then+ redis.call('EXPIRE', KEYS[1], ARGV[2])+end+return count+"""-def decrement_monthly_combined_search_api(user_id: int) -> None:- """Refund one keyed combined-search increment. Never drops below 0."""- key = _combined_search_api_monthly_key(user_id)- try:- if cache.get(key, default=0) > 0:- cache.decr(key)- except ValueError:- # decr() raises if the key vanished between the get and the decr; ignore.- pass+def increment_monthly_combined_search_api_if_below(user_id: int, limit: int) -> int | None:+ """Count one keyed (billed) combined-search request if the user is below `limit`.++ Returns the new count, or None when the user is already at the limit, in which case+ nothing is counted: the counter never goes over the limit, even for an instant.+ Requires the django-redis cache backend.+ """+ key = cache.make_key(_combined_search_api_monthly_key(user_id))+ conn = get_redis_connection("default")+ count = conn.eval(_INCREMENT_IF_BELOW_LIMIT, 1, key, limit, MONTHLY_TTL)+ return None if count == -1 else count# ---------------------------------------------------------------------------@@ -181,12 +193,17 @@ def decrement_monthly_combined_search_api(user_id: int) -> None:def _scan_current_month_keys(prefix: str) -> list[str]:- now = datetime.now(timezone.utc)- pattern = f"{prefix}:monthly:*:{now.year}:{now.month:02d}"- from django_redis import get_redis_connection+ """Return the cache keys (as passed to cache.get) matching this month's counters.+ Redis holds each cache key under its versioned form (":1:search:...") so the scan+ pattern needs the same prefix, and the prefix comes off the keys it finds.+ """+ now = datetime.now(timezone.utc)+ pattern = cache.make_key(f"{prefix}:monthly:*:{now.year}:{now.month:02d}")+ redis_prefix = cache.make_key("")conn = get_redis_connection("default")- return [k.decode() if isinstance(k, bytes) else k for k in conn.scan_iter(pattern)]+ redis_keys = [k.decode() if isinstance(k, bytes) else k for k in conn.scan_iter(pattern)]+ return [k.removeprefix(redis_prefix) for k in redis_keys]def get_all_monthly_keys() -> list[str]:diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.pyindex 39607fd..9736517 100644--- a/mwmbl/tinysearchengine/combined_search.py+++ b/mwmbl/tinysearchengine/combined_search.py@@ -40,10 +40,9 @@ from mwmbl.models import Membership, UserBillingfrom mwmbl.quota import (check_rate_limit,decrement_monthly_combined_search,- decrement_monthly_combined_search_api,get_monthly_count,increment_monthly_combined_search,- increment_monthly_combined_search_api,+ increment_monthly_combined_search_api_if_below,)from mwmbl.search_auth import authenticate_userfrom mwmbl.search_setup import index_path@@ -164,25 +163,26 @@ def init_router(ranker) -> None:# the spend limit; web requests use the membership quota. Each has its own counter.if request.headers.get("X-API-Key"):monthly_limit = await sync_to_async(_keyed_monthly_limit)(user)- increment, decrement = increment_monthly_combined_search_api, decrement_monthly_combined_search_api- over_limit_message = (- f"Combined Search monthly quota exceeded: your spend limit allows {monthly_limit:,} "- "requests this month. Increase your monthly spend limit at https://mwmbl.org/pricing "- "to allow more."- )+ # Billed requests are counted only when under the limit, so the counter that+ # sync_search_counts copies to Postgres, and Polar bills, never holds a refused one.+ monthly_usage = await sync_to_async(increment_monthly_combined_search_api_if_below)(user.id, monthly_limit)+ if monthly_usage is None:+ raise HttpError(+ 429,+ f"Combined Search monthly quota exceeded: your spend limit allows {monthly_limit:,} "+ "requests this month. Increase your monthly spend limit at https://mwmbl.org/pricing "+ "to allow more.",+ )else:tier = await Membership.objects.filter(user=user).values_list("tier", flat=True).afirst()monthly_limit = combined_search_monthly_limit(tier)- increment, decrement = increment_monthly_combined_search, decrement_monthly_combined_search- over_limit_message = f"Combined Search monthly quota exceeded: {monthly_limit} requests per month."-- # Increment first, then check: this makes the quota check atomic under concurrent- # requests (a check-then-increment would let racing requests both pass). Refund the- # increment if the caller is over the limit.- monthly_usage = await sync_to_async(increment)(user.id)- if monthly_usage > monthly_limit:- await sync_to_async(decrement)(user.id)- raise HttpError(429, over_limit_message)+ # Increment first, then check: this makes the quota check atomic under concurrent+ # requests (a check-then-increment would let racing requests both pass). Refund the+ # increment if the caller is over the limit.+ monthly_usage = await sync_to_async(increment_monthly_combined_search)(user.id)+ if monthly_usage > monthly_limit:+ await sync_to_async(decrement_monthly_combined_search)(user.id)+ raise HttpError(429, f"Combined Search monthly quota exceeded: {monthly_limit} requests per month.")# The index lookup doesn't need Staan's answer, so it runs while Staan is in flight# rather than after it. get_staan_results returns [] on failure by itself.diff --git a/test/conftest.py b/test/conftest.pyindex 3fab119..cfe842b 100644--- a/test/conftest.py+++ b/test/conftest.py@@ -11,7 +11,10 @@ callback that runs longer than 100 ms triggers a warning. Combined withaccidental sync calls leaking into async paths."""+import os+import pytest+from django_redis import get_redis_connection@pytest.fixture@@ -31,3 +34,25 @@ def async_debug_loop(event_loop):event_loop.set_debug(True)event_loop.slow_callback_duration = 0.1yield event_loop+++def redis_cache(settings):+ """Point the default cache at a real Redis, emptied before and after the test.++ The test settings use LocMemCache, which can't run the Lua scripts some quota+ counters rely on for atomicity. TEST_REDIS_URL names a Redis database the tests+ may flush, so it must not be one holding data you want to keep.+ """+ redis_url = os.environ["TEST_REDIS_URL"]+ settings.CACHES = {+ "default": {+ "BACKEND": "django_redis.cache.RedisCache",+ "LOCATION": redis_url,+ "OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},+ }+ }+ connection = get_redis_connection("default")+ connection.flushdb()+ yield connection+ connection.flushdb()diff --git a/test/test_combined_search.py b/test/test_combined_search.pyindex 4ce77ba..63a1115 100644--- a/test/test_combined_search.py+++ b/test/test_combined_search.py@@ -160,16 +160,8 @@ def _get_with_key(client, api_key):return client.get(f"{URL}?q=tokio", HTTP_X_API_KEY=api_key.raw_key)-def fresh_keyed_quota(user):- keys = [_combined_search_api_monthly_key(user.id), _monthly_key(user.id)]- cache.delete_many(keys)- yield- cache.delete_many(keys)--@pytest.mark.django_db-def test_an_api_key_without_a_spend_limit_is_refused(client, api_key, fresh_quota, fresh_keyed_quota, stub_sources):+def test_an_api_key_without_a_spend_limit_is_refused(client, api_key, fresh_quota, redis_cache, stub_sources):"""There is no free allowance for keyed Combined Search, so it needs a spend limit."""stub_sources()@@ -181,9 +173,7 @@ def test_an_api_key_without_a_spend_limit_is_refused(client, api_key, fresh_quot@pytest.mark.django_db-def test_a_keyed_request_is_billed_on_its_own_counter(- client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources-):+def test_a_keyed_request_is_billed_on_its_own_counter(client, user, api_key, fresh_quota, redis_cache, stub_sources):stub_sources()UserBilling.objects.create(user=user, max_monthly_spend_cents=1_000)@@ -198,7 +188,7 @@ def test_a_keyed_request_is_billed_on_its_own_counter(@pytest.mark.django_dbdef test_a_member_using_a_key_is_billed_not_given_the_membership_quota(- client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources+ client, user, api_key, fresh_quota, redis_cache, stub_sources):stub_sources()_join(user, MembershipTier.CANOPY)@@ -207,8 +197,8 @@ def test_a_member_using_a_key_is_billed_not_given_the_membership_quota(@pytest.mark.django_db-def test_a_keyed_request_over_the_spend_limit_is_refused_and_refunded(- client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources+def test_a_keyed_request_over_the_spend_limit_is_refused_and_not_counted(+ client, user, api_key, fresh_quota, redis_cache, stub_sources):stub_sources()UserBilling.objects.create(user=user, max_monthly_spend_cents=1_000)@@ -224,7 +214,7 @@ def test_a_keyed_request_over_the_spend_limit_is_refused_and_refunded(@pytest.mark.django_dbdef test_standard_search_overage_uses_up_the_shared_spend_limit(- client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources+ client, user, api_key, fresh_quota, redis_cache, stub_sources):"""$10 buys 2,000 overage requests of standard search; once they are used, nothing isleft of the spend limit for Combined Search."""diff --git a/test/test_quota_redis.py b/test/test_quota_redis.pynew file mode 100644index 0000000..5ece875--- /dev/null+++ b/test/test_quota_redis.py@@ -0,0 +1,155 @@+"""Quota counters and the hourly sync, against a real Redis.++The counter is billed, so it must never hold a request that was refused, not even for an+instant: sync_search_counts copies it to Postgres whenever it runs, and Postgres is the+baseline it is restored from.+"""++import threading+from datetime import datetime, timezone++import pytest+from django.core.cache import cache++from mwmbl.background import sync_search_counts+from mwmbl.models import UsageBucket+from mwmbl.quota import (+ MONTHLY_TTL,+ _combined_search_api_monthly_key,+ _monthly_key,+ delete_all_monthly_keys,+ get_all_combined_search_api_monthly_keys,+ get_all_monthly_keys,+ get_monthly_combined_search_api_count,+ get_monthly_count,+ increment_monthly,+ increment_monthly_combined_search_api_if_below,+)++USER_ID = 42+++def user(django_user_model):+ return django_user_model.objects.create_user(username="quota", email="[email protected]", password="x")+++def test_a_request_below_the_limit_is_counted(redis_cache):+ assert increment_monthly_combined_search_api_if_below(USER_ID, limit=2) == 1+ assert increment_monthly_combined_search_api_if_below(USER_ID, limit=2) == 2++ assert get_monthly_combined_search_api_count(USER_ID) == 2+++def test_a_request_at_the_limit_is_refused_and_not_counted(redis_cache):+ cache.set(_combined_search_api_monthly_key(USER_ID), 2, timeout=MONTHLY_TTL)++ assert increment_monthly_combined_search_api_if_below(USER_ID, limit=2) is None+ assert get_monthly_combined_search_api_count(USER_ID) == 2+++def test_a_counter_already_over_the_limit_is_left_alone(redis_cache):+ """A spend limit lowered mid-month leaves the counter above the new limit."""+ cache.set(_combined_search_api_monthly_key(USER_ID), 5, timeout=MONTHLY_TTL)++ assert increment_monthly_combined_search_api_if_below(USER_ID, limit=2) is None+ assert get_monthly_combined_search_api_count(USER_ID) == 5+++def test_a_zero_limit_counts_nothing(redis_cache):+ assert increment_monthly_combined_search_api_if_below(USER_ID, limit=0) is None+ assert get_monthly_combined_search_api_count(USER_ID) == 0+++def test_a_new_counter_expires_with_the_month(redis_cache):+ increment_monthly_combined_search_api_if_below(USER_ID, limit=10)+ increment_monthly_combined_search_api_if_below(USER_ID, limit=10)++ ttl = redis_cache.ttl(cache.make_key(_combined_search_api_monthly_key(USER_ID)))+ assert MONTHLY_TTL - 5 <= ttl <= MONTHLY_TTL+++def test_concurrent_requests_never_pass_the_limit(redis_cache):+ limit = 25+ results = []+ lock = threading.Lock()++ def request():+ count = increment_monthly_combined_search_api_if_below(USER_ID, limit=limit)+ with lock:+ results.append(count)++ threads = [threading.Thread(target=request) for _ in range(100)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ counted = sorted(count for count in results if count is not None)+ assert counted == list(range(1, limit + 1))+ assert get_monthly_combined_search_api_count(USER_ID) == limit+++def test_the_counter_never_reads_over_the_limit_while_requests_are_refused(redis_cache):+ """This is the read sync_search_counts makes: with increment-then-refund it could catch+ the counter one over the limit, store that in Postgres, and restore it to Redis."""+ limit = 3+ cache.set(_combined_search_api_monthly_key(USER_ID), limit, timeout=MONTHLY_TTL)+ stop = threading.Event()++ def refused_requests():+ while not stop.is_set():+ increment_monthly_combined_search_api_if_below(USER_ID, limit=limit)++ workers = [threading.Thread(target=refused_requests) for _ in range(4)]+ for worker in workers:+ worker.start()+ try:+ reads = [get_monthly_combined_search_api_count(USER_ID) for _ in range(2_000)]+ finally:+ stop.set()+ for worker in workers:+ worker.join()++ assert max(reads) == limit+++def test_sync_stores_the_counted_requests_in_postgres(redis_cache, user):+ for _ in range(3):+ increment_monthly_combined_search_api_if_below(user.id, limit=3)+ increment_monthly_combined_search_api_if_below(user.id, limit=3)++ sync_search_counts.now()++ now = datetime.now(timezone.utc)+ bucket = UsageBucket.objects.get(user=user, year=now.year, month=now.month)+ assert bucket.combined_search_count == 3+++def test_the_scans_find_the_counters_the_cache_wrote(redis_cache):+ """Redis stores cache keys with a version prefix, which the scan pattern must include."""+ increment_monthly(USER_ID)+ increment_monthly_combined_search_api_if_below(USER_ID, limit=1)++ assert get_all_monthly_keys() == [_monthly_key(USER_ID)]+ assert get_all_combined_search_api_monthly_keys() == [_combined_search_api_monthly_key(USER_ID)]+++def test_delete_all_monthly_keys_deletes_the_counters(redis_cache):+ increment_monthly(USER_ID)++ delete_all_monthly_keys()++ assert get_monthly_count(USER_ID) == 0+++def test_sync_stores_standard_search_counts_in_postgres(redis_cache, user):+ for _ in range(4):+ increment_monthly(user.id)++ sync_search_counts.now()++ now = datetime.now(timezone.utc)+ assert UsageBucket.objects.get(user=user, year=now.year, month=now.month).count == 4