Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Bill keyed Combined Search against the spend limit as its own Polar meter

Claudee7412481c42c
diff --git a/mwmbl/background.py b/mwmbl/background.py
index 99cf5cd..70f313f 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -31,7 +31,13 @@ from mwmbl.models import DomainEvidence, DomainSubmission, OldIndex, UsageBucket
from mwmbl.moderation.evidence import crawl_domain, store_evidence, store_failure
from mwmbl.moderation.model import reset_model_cache
from mwmbl.moderation.suggest import refresh_suggestion
-from mwmbl.quota import MONTHLY_TTL, _monthly_key, get_all_monthly_keys
+from mwmbl.quota import (
+ MONTHLY_TTL,
+ _combined_search_api_monthly_key,
+ _monthly_key,
+ get_all_combined_search_api_monthly_keys,
+ get_all_monthly_keys,
+)
from mwmbl.tinysearchengine.copy_index import copy_pages
from mwmbl.tinysearchengine.indexer import Document, TinyIndex
@@ -98,37 +104,44 @@ def sync_search_counts():
so Postgres stays current as a durable backup.
"""
now = datetime.now(timezone.utc)
-
- # Step 1: seed Redis from Postgres, taking the max of the two values.
- # Postgres may lag behind (up to one sync interval), so if Redis already has
- # a higher count we keep it. If Redis was cleared (restart), the Postgres
- # value restores the baseline; any requests made since the restart are
- # already counted in Redis and will be included via max().
- for bucket in UsageBucket.objects.filter(year=now.year, month=now.month):
- key = _monthly_key(bucket.user_id, year=now.year, month=now.month)
- if not cache.add(key, bucket.count, timeout=MONTHLY_TTL):
- # Key already exists — only update if the Postgres value is higher
- current = cache.get(key, default=0)
- if bucket.count > current:
- cache.set(key, bucket.count, timeout=MONTHLY_TTL)
-
- # Step 2: sync live Redis counters back to Postgres
- for key in get_all_monthly_keys():
- # key format: search:monthly:{user_id}:{year}:{month}
- try:
- parts = key.split(":")
- user_id = int(parts[2])
- year = int(parts[3])
- month = int(parts[4])
- count = cache.get(key, default=0)
- UsageBucket.objects.update_or_create(
- user_id=user_id,
- year=year,
- month=month,
- defaults={"count": count},
- )
- except Exception:
- logger.exception("Error syncing search count for key %s", key)
+ buckets = list(UsageBucket.objects.filter(year=now.year, month=now.month))
+ # Standard search and keyed Combined Search have a counter each, stored in their own field.
+ counters = [
+ (_monthly_key, get_all_monthly_keys, "count"),
+ (_combined_search_api_monthly_key, get_all_combined_search_api_monthly_keys, "combined_search_count"),
+ ]
+ for key_for, get_all_keys, field in counters:
+ # Step 1: seed Redis from Postgres, taking the max of the two values.
+ # Postgres may lag behind (up to one sync interval), so if Redis already has
+ # a higher count we keep it. If Redis was cleared (restart), the Postgres
+ # value restores the baseline; any requests made since the restart are
+ # already counted in Redis and will be included via max().
+ for bucket in buckets:
+ stored_count = getattr(bucket, field)
+ key = key_for(bucket.user_id, year=now.year, month=now.month)
+ if not cache.add(key, stored_count, timeout=MONTHLY_TTL):
+ # Key already exists — only update if the Postgres value is higher
+ current = cache.get(key, default=0)
+ if stored_count > current:
+ cache.set(key, stored_count, timeout=MONTHLY_TTL)
+
+ # Step 2: sync live Redis counters back to Postgres
+ for key in get_all_keys():
+ # key format: {prefix}:monthly:{user_id}:{year}:{month}
+ try:
+ parts = key.split(":")
+ user_id = int(parts[2])
+ year = int(parts[3])
+ month = int(parts[4])
+ count = cache.get(key, default=0)
+ UsageBucket.objects.update_or_create(
+ user_id=user_id,
+ year=year,
+ month=month,
+ defaults={field: count},
+ )
+ except Exception:
+ logger.exception("Error syncing search count for key %s", key)
# ---------------------------------------------------------------------------
@@ -181,7 +194,7 @@ def purge_blacklisted_from_queue():
def report_usage_to_polar():
"""
Reports each user's billable overage (requests beyond the free 2,000/month)
- to Polar as usage events, once per hour.
+ and keyed Combined Search requests to Polar as usage events, once per hour.
Only the delta since the last report is sent (UsageBucket.reported_overage
tracks how much has already been ingested), so re-runs are idempotent and a
@@ -200,18 +213,24 @@ def report_usage_to_polar():
continue # no Polar customer yet — nothing to report
total_overage = pricing.billable_overage(bucket.count)
- delta = total_overage - bucket.reported_overage
- if delta <= 0:
+ search_delta = total_overage - bucket.reported_overage
+ # Keyed Combined Search has no free allowance, so every request is billable. It is
+ # its own event so that Polar can meter and price it apart from standard search.
+ combined_search_delta = bucket.combined_search_count - bucket.reported_combined_search
+ if search_delta <= 0 and combined_search_delta <= 0:
continue
- events.append(
- {
- "name": "search_request",
- "external_customer_id": str(bucket.user.id),
- "metadata": {"quantity": delta},
- }
- )
- bucket.reported_overage = total_overage
+ for name, delta in [("search_request", search_delta), ("combined_search_request", combined_search_delta)]:
+ if delta > 0:
+ events.append(
+ {
+ "name": name,
+ "external_customer_id": str(bucket.user.id),
+ "metadata": {"quantity": delta},
+ }
+ )
+ bucket.reported_overage = max(total_overage, bucket.reported_overage)
+ bucket.reported_combined_search = max(bucket.combined_search_count, bucket.reported_combined_search)
buckets_to_update.append(bucket)
if not events:
@@ -224,7 +243,7 @@ def report_usage_to_polar():
logger.exception("Error reporting usage to Polar")
return
- UsageBucket.objects.bulk_update(buckets_to_update, ["reported_overage"])
+ UsageBucket.objects.bulk_update(buckets_to_update, ["reported_overage", "reported_combined_search"])
# ---------------------------------------------------------------------------
diff --git a/mwmbl/migrations/0041_usagebucket_combined_search.py b/mwmbl/migrations/0041_usagebucket_combined_search.py
new file mode 100644
index 0000000..434d023
--- /dev/null
+++ b/mwmbl/migrations/0041_usagebucket_combined_search.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.13 on 2026-10-03 14:04
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mwmbl", "0040_membership"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="usagebucket",
+ name="combined_search_count",
+ field=models.IntegerField(default=0),
+ ),
+ migrations.AddField(
+ model_name="usagebucket",
+ name="reported_combined_search",
+ field=models.IntegerField(default=0),
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 939b2f0..233c986 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -210,6 +210,10 @@ class UsageBucket(models.Model):
# ingested to Polar as usage events for this month. Lets the reporting job
# send only the incremental delta each run, idempotently.
reported_overage = models.IntegerField(default=0)
+ # Keyed Combined Search requests, which are billed from the first one and reported to
+ # Polar as their own event, so they are counted and tracked apart from the above.
+ combined_search_count = models.IntegerField(default=0)
+ reported_combined_search = models.IntegerField(default=0)
class Meta:
unique_together = [("user", "year", "month")]
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 5804320..c469f93 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -85,7 +85,7 @@ from mwmbl.platform.schemas import (
VoteStatsRequest,
)
from mwmbl.polar_webhooks import validate_event
-from mwmbl.quota import get_monthly_combined_search_count
+from mwmbl.quota import get_monthly_combined_search_api_count, get_monthly_combined_search_count
from mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cache
from mwmbl.signals import schedule_blacklist_rebuild
from mwmbl.usernames import generate_username
@@ -1223,12 +1223,15 @@ def _subscription_response(user, billing, status: str) -> SubscriptionResponse:
spend_cents = billing.max_monthly_spend_cents if billing else 0
usage = get_monthly_count(user.id)
+ combined_search_usage = get_monthly_combined_search_api_count(user.id)
return SubscriptionResponse(
status=status,
max_monthly_spend_cents=spend_cents,
- monthly_limit=pricing.effective_monthly_request_cap(spend_cents),
+ monthly_limit=pricing.effective_monthly_request_cap(spend_cents, combined_search_usage),
monthly_usage=usage,
- estimated_cost_cents=pricing.estimated_cost_cents(usage),
+ combined_search_monthly_limit=pricing.combined_search_monthly_cap(spend_cents, usage),
+ combined_search_monthly_usage=combined_search_usage,
+ estimated_cost_cents=pricing.estimated_cost_cents(usage, combined_search_usage),
current_period_end=billing.current_period_end if billing else None,
polar_customer_id=billing.polar_customer_id if billing else None,
)
diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.py
index f7f19ab..f6ff659 100644
--- a/mwmbl/platform/schemas.py
+++ b/mwmbl/platform/schemas.py
@@ -29,6 +29,8 @@ class SubscriptionResponse(Schema):
max_monthly_spend_cents: int
monthly_limit: int
monthly_usage: int
+ combined_search_monthly_limit: int
+ combined_search_monthly_usage: int
estimated_cost_cents: int
current_period_end: Optional[datetime]
polar_customer_id: Optional[str]
diff --git a/mwmbl/pricing.py b/mwmbl/pricing.py
index cb8298e..3ed9f05 100644
--- a/mwmbl/pricing.py
+++ b/mwmbl/pricing.py
@@ -7,30 +7,56 @@ import cycles.
FREE_KEYED_MONTHLY_LIMIT = 2_000 # free requests/month once an API key is presented
PRICE_PER_1000_QUERIES_CENTS = 500 # $5.00 per 1,000 queries
+# Keyed Combined Search is billed from the first request: it costs us on every request (EUSP
+# and the LLM judge), so it has no free allowance. The same price as standard search for
+# now, but metered separately in Polar so the two can diverge.
+COMBINED_SEARCH_PRICE_PER_1000_QUERIES_CENTS = 500
# Preset spend-limit options surfaced in the UI (mirrors Brave's Free/$10/$25/$100 presets).
SPEND_LIMIT_PRESETS_CENTS = [0, 1_000, 2_500, 10_000]
-def effective_monthly_request_cap(max_monthly_spend_cents: int) -> int:
+def effective_monthly_request_cap(max_monthly_spend_cents: int, combined_search_count: int = 0) -> int:
"""Total requests/month a keyed user may make before being blocked.
Equal to the free allowance plus however many additional requests the
- configured spend limit buys at $5.00/1,000 requests. Uses integer
- arithmetic (`* 1000 // PRICE_PER_1000_QUERIES_CENTS`) to avoid rounding
+ configured spend limit buys at $5.00/1,000 requests, once this month's keyed
+ Combined Search spend is taken out of it - the two share the one limit. Uses
+ integer arithmetic (`* 1000 // PRICE_PER_1000_QUERIES_CENTS`) to avoid rounding
drift from fractional-cent-per-request division.
"""
- if max_monthly_spend_cents <= 0:
+ remaining_cents = max_monthly_spend_cents - _cost_cents_rounded_up(
+ combined_search_count, COMBINED_SEARCH_PRICE_PER_1000_QUERIES_CENTS
+ )
+ if remaining_cents <= 0:
return FREE_KEYED_MONTHLY_LIMIT
- paid_requests = (max_monthly_spend_cents * 1000) // PRICE_PER_1000_QUERIES_CENTS
+ paid_requests = (remaining_cents * 1000) // PRICE_PER_1000_QUERIES_CENTS
return FREE_KEYED_MONTHLY_LIMIT + paid_requests
+def combined_search_monthly_cap(max_monthly_spend_cents: int, search_count: int) -> int:
+ """Keyed Combined Search requests/month the spend limit allows.
+
+ What is left of the spend limit once this month's standard-search overage is taken
+ out. Each endpoint rounds the other's spend up, so together they never bill more
+ than the limit.
+ """
+ search_spend_cents = _cost_cents_rounded_up(billable_overage(search_count), PRICE_PER_1000_QUERIES_CENTS)
+ remaining_cents = max(0, max_monthly_spend_cents - search_spend_cents)
+ return (remaining_cents * 1000) // COMBINED_SEARCH_PRICE_PER_1000_QUERIES_CENTS
+
+
+def _cost_cents_rounded_up(count: int, price_per_1000_cents: int) -> int:
+ return -(-count * price_per_1000_cents // 1000)
+
+
def billable_overage(monthly_count: int) -> int:
"""Number of requests in the current month that are billable (beyond the free allowance)."""
return max(0, monthly_count - FREE_KEYED_MONTHLY_LIMIT)
-def estimated_cost_cents(monthly_count: int) -> int:
+def estimated_cost_cents(monthly_count: int, combined_search_count: int = 0) -> int:
"""Estimated cost in cents for the current month's usage, rounded down."""
- return (billable_overage(monthly_count) * PRICE_PER_1000_QUERIES_CENTS) // 1000
+ search_cost = billable_overage(monthly_count) * PRICE_PER_1000_QUERIES_CENTS
+ combined_search_cost = combined_search_count * COMBINED_SEARCH_PRICE_PER_1000_QUERIES_CENTS
+ return (search_cost + combined_search_cost) // 1000
diff --git a/mwmbl/quota.py b/mwmbl/quota.py
index 9fd4f47..f9dde07 100644
--- a/mwmbl/quota.py
+++ b/mwmbl/quota.py
@@ -41,6 +41,13 @@ def _combined_search_monthly_key(user_id: int, year: int | None = None, month: i
return f"combined_search:monthly:{user_id}:{y}:{m:02d}"
+def _combined_search_api_monthly_key(user_id: int, year: int | None = None, month: int | None = None) -> str:
+ now = datetime.now(timezone.utc)
+ y = year if year is not None else now.year
+ m = month if month is not None else now.month
+ return f"combined_search_api:monthly:{user_id}:{y}:{m:02d}"
+
+
def _rate_key(user_id: int) -> str:
return f"search:rate:{user_id}"
@@ -144,23 +151,56 @@ def decrement_monthly_combined_search(user_id: int) -> None:
pass
+def get_monthly_combined_search_api_count(user_id: int) -> int:
+ """Return the current monthly keyed (billed) combined-search count for a user (0 if not set)."""
+ 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)
+
+
+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
+
+
# ---------------------------------------------------------------------------
# Key scanning (used by background jobs only — requires django-redis)
# ---------------------------------------------------------------------------
+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
+
+ conn = get_redis_connection("default")
+ return [k.decode() if isinstance(k, bytes) else k for k in conn.scan_iter(pattern)]
+
+
def get_all_monthly_keys() -> list[str]:
"""
Return all active monthly counter keys for the current month.
Uses the underlying Redis SCAN command via django-redis.
Only call this from background tasks, not from request handlers.
"""
- now = datetime.now(timezone.utc)
- pattern = f"search:monthly:*:{now.year}:{now.month:02d}"
- from django_redis import get_redis_connection
+ return _scan_current_month_keys("search")
- conn = get_redis_connection("default")
- return [k.decode() if isinstance(k, bytes) else k for k in conn.scan_iter(pattern)]
+
+def get_all_combined_search_api_monthly_keys() -> list[str]:
+ """The keyed combined-search counterpart of get_all_monthly_keys."""
+ return _scan_current_month_keys("combined_search_api")
def delete_all_monthly_keys() -> None:
diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.py
index a166535..39607fd 100644
--- a/mwmbl/tinysearchengine/combined_search.py
+++ b/mwmbl/tinysearchengine/combined_search.py
@@ -32,14 +32,18 @@ from ninja import Router
from ninja.errors import HttpError
from pydantic import Field
+from mwmbl import pricing
from mwmbl.format import format_result_v2
from mwmbl.indexer.index_batches import index_results_against_query
from mwmbl.membership import combined_search_monthly_limit
-from mwmbl.models import Membership
+from mwmbl.models import Membership, UserBilling
from 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,
)
from mwmbl.search_auth import authenticate_user
from mwmbl.search_setup import index_path
@@ -75,9 +79,13 @@ DESCRIPTION = (
"- `eusp` - returned by the European Search Perspective (EUSP) web-search API\n"
"- `wikipedia` - a Wikipedia page from the Mwmbl index\n"
"- `google`, `user` - originally suggested via Google, or submitted by a user\n\n"
- "Authentication is required with a JWT bearer token. A per-user monthly quota applies, "
- "set by the user's membership tier; `monthly_usage` and `monthly_limit` report it on "
- "every response. Access with an API key (`X-API-Key`) is not available yet.\n\n"
+ "Authentication is required: a search-scoped API key in `X-API-Key`, or a JWT bearer "
+ "token. With an API key every request is billed - there is no free allowance - at the "
+ "same price as `/api/v2/search/` overage, within your monthly spend limit, which "
+ "standard search and Combined Search share. Obtain a key via "
+ "`POST /api/v1/platform/api-keys/`. With a JWT, a monthly quota set by your membership "
+ "tier applies instead. `monthly_usage` and `monthly_limit` report whichever applies on "
+ "every response.\n\n"
"EUSP's results are added to the Mwmbl index; `pages_indexed` reports how many new "
"pages that added.\n\n"
"If EUSP is down or unconfigured, the request loses its extra recall, not its "
@@ -118,6 +126,22 @@ def index_staan_results(query: str, staan_results: list[Document]) -> int:
return 0
+def _keyed_monthly_limit(user) -> int:
+ """Keyed Combined Search requests the user's spend limit allows this month.
+
+ There is no free allowance, so a user without a spend limit is refused outright.
+ """
+ billing = UserBilling.objects.filter(user=user).first()
+ spend_cents = billing.max_monthly_spend_cents if billing else 0
+ if spend_cents <= 0:
+ raise HttpError(
+ 402,
+ "Combined Search via API key is billed from the first request. Set a monthly spend "
+ "limit at https://mwmbl.org/pricing to use it.",
+ )
+ return pricing.combined_search_monthly_cap(spend_cents, get_monthly_count(user.id))
+
+
def init_router(ranker) -> None:
@router.get(
"",
@@ -131,28 +155,34 @@ def init_router(ranker) -> None:
)
async def combined_search(request, q: str):
user = await authenticate_user(request)
- # authenticate_user takes the API key over a bearer token whenever the header is
- # present, so this is how the caller authenticated. Combined Search costs us on
- # every request, so it has no free API tier; keyed access comes with metered billing.
- if request.headers.get("X-API-Key"):
- raise HttpError(402, "Combined Search via API key requires a paid plan, which is not available yet.")
if not await sync_to_async(check_rate_limit)(user.id):
raise HttpError(429, "Rate limit exceeded: maximum 5 requests per second.")
- tier = await Membership.objects.filter(user=user).values_list("tier", flat=True).afirst()
- monthly_limit = combined_search_monthly_limit(tier)
+ # authenticate_user takes the API key over a bearer token whenever the header is
+ # present, so this is how the caller authenticated. Keyed requests are billed against
+ # 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."
+ )
+ 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_monthly_combined_search)(user.id)
+ monthly_usage = await sync_to_async(increment)(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 "
- f"and you have used {monthly_usage - 1}.",
- )
+ await sync_to_async(decrement)(user.id)
+ raise HttpError(429, over_limit_message)
# 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/mwmbl/tinysearchengine/search.py b/mwmbl/tinysearchengine/search.py
index da1f56b..8d59d13 100644
--- a/mwmbl/tinysearchengine/search.py
+++ b/mwmbl/tinysearchengine/search.py
@@ -8,7 +8,12 @@ from ninja.errors import HttpError
from mwmbl import pricing
from mwmbl.format import format_result, format_result_v2
from mwmbl.models import MwmblUser
-from mwmbl.quota import check_rate_limit, get_monthly_count, increment_monthly
+from mwmbl.quota import (
+ check_rate_limit,
+ get_monthly_combined_search_api_count,
+ get_monthly_count,
+ increment_monthly,
+)
from mwmbl.search_auth import SearchApiKeyAuth
from mwmbl.tinysearchengine.indexer import TinyIndex
from mwmbl.tinysearchengine.rank import HeuristicRanker
@@ -306,7 +311,9 @@ def _register_search_v2(r: Router | NinjaAPI, ranker: HeuristicRanker):
user: MwmblUser = api_key.user
billing = getattr(user, "billing", None)
spend_cents = billing.max_monthly_spend_cents if billing else 0
- monthly_limit = pricing.effective_monthly_request_cap(spend_cents)
+ monthly_limit = pricing.effective_monthly_request_cap(
+ spend_cents, get_monthly_combined_search_api_count(user.id)
+ )
if not check_rate_limit(user.id):
raise HttpError(
diff --git a/test/test_background_polar_reporting.py b/test/test_background_polar_reporting.py
index c3d8196..65504cc 100644
--- a/test/test_background_polar_reporting.py
+++ b/test/test_background_polar_reporting.py
@@ -132,3 +132,53 @@ def test_report_usage_to_polar_incremental_second_run(billed_user):
bucket.refresh_from_db()
assert bucket.reported_overage == 800
+
+
+def test_report_usage_to_polar_reports_combined_search_as_its_own_event(billed_user):
+ """Keyed Combined Search has no free allowance, so every request is reported."""
+ now = datetime.now(timezone.utc)
+ bucket = UsageBucket.objects.create(
+ user=billed_user,
+ year=now.year,
+ month=now.month,
+ count=pricing.FREE_KEYED_MONTHLY_LIMIT + 500,
+ reported_overage=200,
+ combined_search_count=40,
+ reported_combined_search=10,
+ )
+
+ with patch("polar_sdk.Polar") as MockPolar:
+ mock_polar_instance = MockPolar.return_value.__enter__.return_value
+ report_usage_to_polar.now()
+
+ events = mock_polar_instance.events.ingest.call_args[1]["request"]["events"]
+ quantities = {event["name"]: event["metadata"]["quantity"] for event in events}
+ assert quantities == {"search_request": 300, "combined_search_request": 30}
+
+ bucket.refresh_from_db()
+ assert bucket.reported_overage == 500
+ assert bucket.reported_combined_search == 40
+
+
+def test_report_usage_to_polar_reports_combined_search_within_the_free_allowance(billed_user):
+ now = datetime.now(timezone.utc)
+ bucket = UsageBucket.objects.create(
+ user=billed_user,
+ year=now.year,
+ month=now.month,
+ count=100,
+ combined_search_count=5,
+ )
+
+ with patch("polar_sdk.Polar") as MockPolar:
+ mock_polar_instance = MockPolar.return_value.__enter__.return_value
+ report_usage_to_polar.now()
+
+ events = mock_polar_instance.events.ingest.call_args[1]["request"]["events"]
+ assert [(event["name"], event["metadata"]["quantity"]) for event in events] == [("combined_search_request", 5)]
+
+ bucket.refresh_from_db()
+ assert bucket.reported_overage == 0
+ assert bucket.reported_combined_search == 5
diff --git a/test/test_combined_search.py b/test/test_combined_search.py
index 960fa8d..4ce77ba 100644
--- a/test/test_combined_search.py
+++ b/test/test_combined_search.py
@@ -20,9 +20,16 @@ from django.test import Client, override_settings
from ninja_jwt.tokens import RefreshToken
import mwmbl.tinysearchengine.combined_search as combined_search
+from mwmbl import pricing
from mwmbl.membership import MembershipTier
-from mwmbl.models import ApiKey, Membership, generate_api_key
-from mwmbl.quota import _combined_search_monthly_key
+from mwmbl.models import ApiKey, Membership, UserBilling, generate_api_key
+from mwmbl.quota import (
+ _combined_search_api_monthly_key,
+ _combined_search_monthly_key,
+ _monthly_key,
+ get_monthly_combined_search_api_count,
+ get_monthly_count,
+)
from mwmbl.tinysearchengine.indexer import Document, DocumentSource, DocumentState, TinyIndex
User = get_user_model()
@@ -149,14 +156,83 @@ def test_combined_search_with_jwt(client, access_token, fresh_quota, stub_source
assert response.json()["query"] == "tokio"
+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_is_refused_until_keyed_access_is_billed(client, api_key, fresh_quota, stub_sources):
+def test_an_api_key_without_a_spend_limit_is_refused(client, api_key, fresh_quota, fresh_keyed_quota, stub_sources):
+ """There is no free allowance for keyed Combined Search, so it needs a spend limit."""
stub_sources()
- response = client.get(f"{URL}?q=tokio", HTTP_X_API_KEY=api_key.raw_key)
+ response = _get_with_key(client, api_key)
assert response.status_code == 402
- assert cache.get(_combined_search_monthly_key(api_key.user.id)) is None
+ assert "spend limit" in response.json()["detail"]
+ assert get_monthly_combined_search_api_count(api_key.user.id) == 0
+
+
+def test_a_keyed_request_is_billed_on_its_own_counter(
+ client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources
+):
+ stub_sources()
+ UserBilling.objects.create(user=user, max_monthly_spend_cents=1_000)
+
+ body = _get_with_key(client, api_key).json()
+
+ assert body["monthly_usage"] == 1
+ assert body["monthly_limit"] == pricing.combined_search_monthly_cap(1_000, 0)
+ assert get_monthly_combined_search_api_count(user.id) == 1
+ assert cache.get(_combined_search_monthly_key(user.id)) is None
+ assert get_monthly_count(user.id) == 0
+
+
+def test_a_member_using_a_key_is_billed_not_given_the_membership_quota(
+ client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources
+):
+ stub_sources()
+ _join(user, MembershipTier.CANOPY)
+
+ assert _get_with_key(client, api_key).status_code == 402
+
+
+def test_a_keyed_request_over_the_spend_limit_is_refused_and_refunded(
+ client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources
+):
+ stub_sources()
+ UserBilling.objects.create(user=user, max_monthly_spend_cents=1_000)
+ cap = pricing.combined_search_monthly_cap(1_000, 0)
+ cache.set(_combined_search_api_monthly_key(user.id), cap, timeout=3600)
+
+ response = _get_with_key(client, api_key)
+
+ assert response.status_code == 429
+ assert "spend limit" in response.json()["detail"]
+ assert get_monthly_combined_search_api_count(user.id) == cap
+
+
+def test_standard_search_overage_uses_up_the_shared_spend_limit(
+ client, user, api_key, fresh_quota, fresh_keyed_quota, stub_sources
+):
+ """$10 buys 2,000 overage requests of standard search; once they are used, nothing is
+ left of the spend limit for Combined Search."""
+ stub_sources()
+ UserBilling.objects.create(user=user, max_monthly_spend_cents=1_000)
+ cache.set(_monthly_key(user.id), pricing.FREE_KEYED_MONTHLY_LIMIT + 2_000, timeout=3600)
+
+ assert _get_with_key(client, api_key).status_code == 429
@pytest.mark.django_db
@@ -198,7 +274,7 @@ def test_a_rejected_request_refunds_its_increment(client, user, access_token, fr
@override_settings(COMBINED_SEARCH_MONTHLY_LIMITS={"free": 10})
def test_the_quota_counter_is_its_own(client, user, access_token, fresh_quota, stub_sources):
"""Combined Search must not spend the standard-search or Super Search allowance."""
- from mwmbl.quota import get_monthly_count, get_monthly_super_search_count
+ from mwmbl.quota import get_monthly_super_search_count
stub_sources()
_get(client, access_token)
diff --git a/test/test_pricing.py b/test/test_pricing.py
index 8fe7b92..67a95a5 100644
--- a/test/test_pricing.py
+++ b/test/test_pricing.py
@@ -46,3 +46,46 @@ def test_estimated_cost_cents_below_free_allowance_is_zero():
def test_estimated_cost_cents_above_free_allowance():
# 500 overage requests at $5/1000 = 250 cents
assert pricing.estimated_cost_cents(pricing.FREE_KEYED_MONTHLY_LIMIT + 500) == 250
+
+
+def test_combined_search_has_no_free_allowance():
+ assert pricing.combined_search_monthly_cap(0, 0) == 0
+
+
+def test_combined_search_cap_from_spend_limit():
+ # $10 buys 2,000 Combined Search requests at $5/1000.
+ assert pricing.combined_search_monthly_cap(1_000, 0) == 2_000
+
+
+def test_standard_search_within_the_free_allowance_costs_combined_search_nothing():
+ assert pricing.combined_search_monthly_cap(1_000, pricing.FREE_KEYED_MONTHLY_LIMIT) == 2_000
+
+
+def test_standard_search_overage_comes_out_of_the_combined_search_cap():
+ # 1,000 overage requests cost $5, leaving $5 for 1,000 Combined Search requests.
+ assert pricing.combined_search_monthly_cap(1_000, pricing.FREE_KEYED_MONTHLY_LIMIT + 1_000) == 1_000
+
+
+def test_combined_search_spend_comes_out_of_the_standard_search_cap():
+ assert pricing.effective_monthly_request_cap(1_000, combined_search_count=1_000) == 2_000 + 1_000
+
+
+def test_combined_search_spend_never_takes_the_free_allowance():
+ assert pricing.effective_monthly_request_cap(1_000, combined_search_count=5_000) == 2_000
+
+
+def test_the_two_caps_together_never_exceed_the_spend_limit():
+ # Odd counts cost fractional cents; each cap rounds the other endpoint's spend up.
+ spend_cents = 1_001
+ for other_count in (0, 1, 3, 777):
+ search_cap = pricing.effective_monthly_request_cap(spend_cents, combined_search_count=other_count)
+ assert pricing.estimated_cost_cents(search_cap, other_count) <= spend_cents
+
+ search_count = pricing.FREE_KEYED_MONTHLY_LIMIT + other_count
+ combined_search_cap = pricing.combined_search_monthly_cap(spend_cents, search_count)
+ assert pricing.estimated_cost_cents(search_count, combined_search_cap) <= spend_cents
+
+
+def test_estimated_cost_includes_combined_search():
+ # 500 overage requests and 500 Combined Search requests, each at $5/1000.
+ assert pricing.estimated_cost_cents(pricing.FREE_KEYED_MONTHLY_LIMIT + 500, 500) == 500
diff --git a/test/test_search_api_key.py b/test/test_search_api_key.py
index a51b7a1..5621654 100644
--- a/test/test_search_api_key.py
+++ b/test/test_search_api_key.py
@@ -24,7 +24,15 @@ from ninja_jwt.tokens import RefreshToken
from mwmbl import pricing
from mwmbl.background import sync_search_counts
from mwmbl.models import AgreementType, ApiKey, UsageBucket, UserAgreement, UserBilling, generate_api_key
-from mwmbl.quota import RATE_LIMIT, _monthly_key, check_rate_limit, get_monthly_count, increment_monthly
+from mwmbl.quota import (
+ RATE_LIMIT,
+ _combined_search_api_monthly_key,
+ _monthly_key,
+ check_rate_limit,
+ get_monthly_combined_search_api_count,
+ get_monthly_count,
+ increment_monthly,
+)
User = get_user_model()
@@ -458,6 +466,24 @@ def test_search_keyed_with_spend_limit_raises_cap(api_client, search_api_key, ve
assert response.status_code == 429
+def test_search_keyed_cap_shrinks_with_combined_search_spend(api_client, search_api_key, verified_user):
+ """Standard search and keyed Combined Search share the one spend limit."""
+ UserBilling.objects.create(user=verified_user, max_monthly_spend_cents=1_000)
+ expected_cap = pricing.effective_monthly_request_cap(1_000, combined_search_count=1_000)
+
+ with (
+ patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=True),
+ patch("mwmbl.tinysearchengine.search.get_monthly_combined_search_api_count", return_value=1_000),
+ patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=expected_cap),
+ ):
+ response = api_client.get(
+ "/api/v2/search/?q=python",
+ **api_key_header(search_api_key.raw_key),
+ )
+ assert response.status_code == 429
+
+
# ---------------------------------------------------------------------------
# Crawler /results — header vs body key and scope enforcement
# ---------------------------------------------------------------------------
@@ -648,7 +674,10 @@ def test_sync_search_counts_redis_to_postgres(verified_user):
key = _monthly_key(verified_user.id)
cache.set(key, 42, timeout=3600)
- with patch("mwmbl.background.get_all_monthly_keys", return_value=[key]):
+ with (
+ patch("mwmbl.background.get_all_monthly_keys", return_value=[key]),
+ patch("mwmbl.background.get_all_combined_search_api_monthly_keys", return_value=[]),
+ ):
sync_search_counts.now()
bucket = UsageBucket.objects.get(user=verified_user, year=now.year, month=now.month)
@@ -668,7 +697,10 @@ def test_sync_search_counts_seeds_redis_from_postgres(verified_user):
UsageBucket.objects.create(user=verified_user, year=now.year, month=now.month, count=99)
cache.delete(key)
- with patch("mwmbl.background.get_all_monthly_keys", return_value=[]):
+ with (
+ patch("mwmbl.background.get_all_monthly_keys", return_value=[]),
+ patch("mwmbl.background.get_all_combined_search_api_monthly_keys", return_value=[]),
+ ):
sync_search_counts.now()
assert get_monthly_count(verified_user.id) == 99
@@ -688,7 +720,10 @@ def test_sync_search_counts_uses_postgres_value_when_higher(verified_user):
UsageBucket.objects.create(user=verified_user, year=now.year, month=now.month, count=70)
cache.set(key, 5, timeout=3600)
- with patch("mwmbl.background.get_all_monthly_keys", return_value=[]):
+ with (
+ patch("mwmbl.background.get_all_monthly_keys", return_value=[]),
+ patch("mwmbl.background.get_all_combined_search_api_monthly_keys", return_value=[]),
+ ):
sync_search_counts.now()
assert get_monthly_count(verified_user.id) == 70
@@ -707,7 +742,10 @@ def test_sync_search_counts_keeps_redis_value_when_higher(verified_user):
UsageBucket.objects.create(user=verified_user, year=now.year, month=now.month, count=70)
cache.set(key, 85, timeout=3600)
- with patch("mwmbl.background.get_all_monthly_keys", return_value=[]):
+ with (
+ patch("mwmbl.background.get_all_monthly_keys", return_value=[]),
+ patch("mwmbl.background.get_all_combined_search_api_monthly_keys", return_value=[]),
+ ):
sync_search_counts.now()
assert get_monthly_count(verified_user.id) == 85
@@ -715,6 +753,34 @@ def test_sync_search_counts_keeps_redis_value_when_higher(verified_user):
cache.delete(key)
+def test_sync_search_counts_syncs_the_combined_search_counter(verified_user):
+ """The keyed Combined Search counter goes to its own field and is restored from it."""
+ now = datetime.now(stdlib_timezone.utc)
+ key = _combined_search_api_monthly_key(verified_user.id)
+ cache.set(key, 12, timeout=3600)
+
+ with (
+ patch("mwmbl.background.get_all_monthly_keys", return_value=[]),
+ patch("mwmbl.background.get_all_combined_search_api_monthly_keys", return_value=[key]),
+ ):
+ sync_search_counts.now()
+
+ bucket = UsageBucket.objects.get(user=verified_user, year=now.year, month=now.month)
+ assert bucket.combined_search_count == 12
+ assert bucket.count == 0
+
+ cache.delete(key)
+ with (
+ patch("mwmbl.background.get_all_monthly_keys", return_value=[]),
+ patch("mwmbl.background.get_all_combined_search_api_monthly_keys", return_value=[]),
+ ):
+ sync_search_counts.now()
+
+ assert get_monthly_combined_search_api_count(verified_user.id) == 12
+ cache.delete(key)
+
+
# ---------------------------------------------------------------------------
# Subscription endpoint — GET /api/v1/platform/billing/subscription
# ---------------------------------------------------------------------------