An open source, non-profit web search engine
Switch API pricing from subscription tiers to usage-based billing
Daoud Clarke08e5e3d2e7f6
diff --git a/mwmbl/admin.py b/mwmbl/admin.pyindex 214a21f..1658056 100644--- a/mwmbl/admin.py+++ b/mwmbl/admin.py@@ -3,7 +3,7 @@ from django.contrib import adminfrom django.contrib.admin import ModelAdminfrom django.contrib.auth.admin import UserAdmin-from mwmbl.models import MwmblUser, OldIndex, Curation, FlagCuration, DomainSubmission, ApiKey, MarketingConsent, generate_api_key+from mwmbl.models import MwmblUser, OldIndex, Curation, FlagCuration, DomainSubmission, ApiKey, MarketingConsent, UserBilling, generate_api_keyclass ApiKeyForm(forms.ModelForm):@@ -56,5 +56,12 @@ class MarketingConsentAdmin(ModelAdmin):readonly_fields = ("user", "source", "opted_in", "timestamp")+class UserBillingAdmin(ModelAdmin):+ list_display = ("user", "max_monthly_spend_cents", "polar_customer_id", "current_period_end", "cancel_at_period_end")+ readonly_fields = ("polar_customer_id", "polar_subscription_id", "current_period_end")+ search_fields = ("user__username", "user__email", "polar_customer_id")++admin.site.register(ApiKey, ApiKeyAdmin)admin.site.register(MarketingConsent, MarketingConsentAdmin)+admin.site.register(UserBilling, UserBillingAdmin)diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex e5f1b07..dd2243e 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -67,14 +67,19 @@ class MwmblConfig(AppConfig):try:from background_task.models import Task- from mwmbl.background import sync_search_counts+ from mwmbl.background import sync_search_counts, report_usage_to_polarSYNC_TASK = "mwmbl.background.sync_search_counts"+ POLAR_REPORT_TASK = "mwmbl.background.report_usage_to_polar"# Sync search counts once per hour (3600 seconds)if not Task.objects.filter(task_name=SYNC_TASK).exists():sync_search_counts(repeat=3600, repeat_until=None)+ # Report billable usage overage to Polar once per hour (3600 seconds)+ if not Task.objects.filter(task_name=POLAR_REPORT_TASK).exists():+ report_usage_to_polar(repeat=3600, repeat_until=None)+except Exception:# Don't prevent startup if background task scheduling failslog.exception("Failed to schedule background tasks")diff --git a/mwmbl/background.py b/mwmbl/background.pyindex 50cca81..8b9b282 100644--- a/mwmbl/background.py+++ b/mwmbl/background.py@@ -3,6 +3,7 @@ Script that updates data in a background process.Also contains Django Background Tasks for periodic quota maintenance:- sync_search_counts: syncs Redis monthly counters → DB once per hour+ - report_usage_to_polar: reports billable usage overage to Polar once per hour"""import loggingimport sys@@ -15,6 +16,7 @@ from background_task import backgroundfrom django.conf import settingsfrom django.core.cache import cache+from mwmbl import pricingfrom mwmbl.indexer import index_batches, historicalfrom mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.models import OldIndex, UsageBucket@@ -131,3 +133,49 @@ def sync_search_counts():logger.exception("Error syncing search count for key %s", key)+@background(schedule=0)+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.++ 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+ failed batch simply gets resent (larger) on the next run rather than risking+ double-counting.+ """+ from polar_sdk import Polar++ now = datetime.now(timezone.utc)++ events = []+ buckets_to_update = []+ for bucket in UsageBucket.objects.filter(year=now.year, month=now.month).select_related("user__billing"):+ billing = getattr(bucket.user, "billing", None)+ if not billing or not billing.polar_customer_id:+ continue # no Polar customer yet — nothing to report++ total_overage = pricing.billable_overage(bucket.count)+ delta = total_overage - bucket.reported_overage+ if delta <= 0:+ continue++ events.append({+ "name": "search_request",+ "external_customer_id": str(bucket.user.id),+ "metadata": {"quantity": delta},+ })+ bucket.reported_overage = total_overage+ buckets_to_update.append(bucket)++ if not events:+ return++ try:+ with Polar(access_token=settings.POLAR_ACCESS_TOKEN, server=settings.POLAR_SERVER) as polar:+ polar.events.ingest(request={"events": events})+ except Exception:+ logger.exception("Error reporting usage to Polar")+ return++ UsageBucket.objects.bulk_update(buckets_to_update, ["reported_overage"])diff --git a/mwmbl/migrations/0030_remove_mwmbluser_tier_usagebucket_reported_overage_and_more.py b/mwmbl/migrations/0030_remove_mwmbluser_tier_usagebucket_reported_overage_and_more.pynew file mode 100644index 0000000..d2c99cb--- /dev/null+++ b/mwmbl/migrations/0030_remove_mwmbluser_tier_usagebucket_reported_overage_and_more.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.13 on 2026-07-28 16:24++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('mwmbl', '0029_delete_supersearchbanditstate'),+ ]++ operations = [+ migrations.RemoveField(+ model_name='mwmbluser',+ name='tier',+ ),+ migrations.AddField(+ model_name='usagebucket',+ name='reported_overage',+ field=models.IntegerField(default=0),+ ),+ migrations.AddField(+ model_name='userbilling',+ name='max_monthly_spend_cents',+ field=models.IntegerField(default=0),+ ),+ ]diff --git a/mwmbl/models.py b/mwmbl/models.pyindex 862c732..ee103d2 100644--- a/mwmbl/models.py+++ b/mwmbl/models.py@@ -12,22 +12,7 @@ from mwmbl.usernames import generate_usernameclass MwmblUser(AbstractUser):- class Tier(models.TextChoices):- FREE = "free", "Free"- STARTER = "starter", "Starter"- PRO = "pro", "Pro"-- TIER_MONTHLY_LIMITS = {- Tier.FREE: 1_000,- Tier.STARTER: 10_000,- Tier.PRO: 50_000,- }-- tier = models.CharField(- max_length=20,- choices=Tier.choices,- default=Tier.FREE,- )+ passclass UserCuration(models.Model):@@ -172,6 +157,10 @@ class UsageBucket(models.Model):year = models.IntegerField()month = models.IntegerField()count = models.IntegerField(default=0)+ # How many billable (over-the-free-allowance) requests have already been+ # 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)class Meta:unique_together = [('user', 'year', 'month')]@@ -186,6 +175,9 @@ class UserBilling(models.Model):polar_subscription_id = models.CharField(max_length=100, blank=True, default="")current_period_end = models.DateTimeField(null=True, blank=True)cancel_at_period_end = models.BooleanField(default=False)+ # Maximum amount (in cents) the account may be billed per month for metered+ # usage beyond the free allowance. 0 = free-tier-only (hard capped).+ max_monthly_spend_cents = models.IntegerField(default=0)class AgreementType(models.TextChoices):diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex 12c5d56..bda2362 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -11,17 +11,18 @@ from ninja.pagination import paginatefrom ninja_jwt.authentication import JWTAuthfrom polar_sdk import Polarfrom polar_sdk import models as polar_models-from polar_sdk.models import SubscriptionCancel, CustomerSubscriptionUpdateProduct+from polar_sdk.models import SubscriptionCancelfrom polar_sdk.webhooks import validate_event, WebhookVerificationErrorfrom mwmbl.exceptions import InvalidRequestfrom mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cache+from mwmbl import pricingfrom mwmbl.models import AgreementType, MwmblUser, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling, UserAgreement, MarketingConsent, MarketingSource, generate_usernamefrom mwmbl.platform.schemas import (Registration, ConfirmEmail, DomainSubmissionSchema, UpdateDomainSubmission,VoteRequest, VoteRemoveRequest, VoteStatsRequest, VoteResponse, VoteStats, UserVoteHistory,CreateApiKeyRequest, ApiKeyCreatedResponse, ApiKeyListItem,- UserProfileResponse, SubscriptionResponse, CheckoutRequest, CheckoutResponse, ChangePlanRequest,+ UserProfileResponse, SubscriptionResponse, CheckoutRequest, CheckoutResponse, UpdateSpendLimitRequest,ForgotPasswordRequest, ResetPasswordRequest,AgreementAcceptRequest, AgreementResponse,MarketingConsentRequest, MarketingConsentResponse, MarketingConsentListResponse,@@ -672,17 +673,19 @@ def delete_api_key(request, key_id: int):auth=JWTAuth(),response=UserProfileResponse,summary="Get current user profile",- description="Returns the authenticated user's username, email, plan tier, and email confirmation status.",+ description="Returns the authenticated user's username, email, plan, and email confirmation status.",tags=["Users"],)def get_current_user(request):check_email_verified(request)user = request.user+ billing = getattr(user, "billing", None)+ spend_cents = billing.max_monthly_spend_cents if billing else 0email_address = user.emailaddress_set.first()return UserProfileResponse(username=user.username,email=user.email,- plan=user.tier,+ plan="free" if spend_cents == 0 else "pay-as-you-go",email_confirmed=email_address.verified if email_address else False,)@@ -691,34 +694,41 @@ def get_current_user(request):# Billing# ---------------------------------------------------------------------------+def _subscription_response(user, billing, status: str) -> SubscriptionResponse:+ from mwmbl.quota import get_monthly_count+ spend_cents = billing.max_monthly_spend_cents if billing else 0+ usage = get_monthly_count(user.id)+ return SubscriptionResponse(+ status=status,+ max_monthly_spend_cents=spend_cents,+ monthly_limit=pricing.effective_monthly_request_cap(spend_cents),+ monthly_usage=usage,+ estimated_cost_cents=pricing.estimated_cost_cents(usage),+ current_period_end=billing.current_period_end if billing else None,+ polar_customer_id=billing.polar_customer_id if billing else None,+ )++@router.get("/billing/subscription",auth=JWTAuth(),response=SubscriptionResponse,summary="Get current subscription",- description="Returns the user's active plan, quota, and current-period usage.",+ description="Returns the user's spend limit, quota, and current-period usage.",tags=["Billing"],)def get_subscription(request):- from mwmbl.quota import get_monthly_countcheck_email_verified(request)user = request.userbilling = getattr(user, "billing", None)- usage = get_monthly_count(user.id)- if user.tier == MwmblUser.Tier.FREE:+ spend_cents = billing.max_monthly_spend_cents if billing else 0+ if spend_cents == 0:status = "free"elif billing and billing.cancel_at_period_end:status = "canceling"else:status = "active"- return SubscriptionResponse(- plan=user.tier,- status=status,- monthly_limit=MwmblUser.TIER_MONTHLY_LIMITS[user.tier],- monthly_usage=usage,- current_period_end=billing.current_period_end if billing else None,- polar_customer_id=billing.polar_customer_id if billing else None,- )+ return _subscription_response(user, billing, status)@router.post(@@ -731,20 +741,14 @@ def get_subscription(request):)def create_checkout(request, body: CheckoutRequest):check_email_verified(request)- product_map = {- "starter": settings.POLAR_PRODUCT_ID_STARTER,- "pro": settings.POLAR_PRODUCT_ID_PRO,- }- product_id = product_map[body.plan]+ product_id = settings.POLAR_PRODUCT_ID_USAGEif not product_id:- raise InvalidRequest(f"Plan '{body.plan}' is not configured. Contact support.", status=503)- billing = getattr(request.user, "billing", None)+ raise InvalidRequest("Billing is not configured. Contact support.", status=503)checkout_params = {"products": [product_id],+ "external_customer_id": str(request.user.id),"metadata": {"user_id": str(request.user.id)},}- if billing and billing.polar_customer_id:- checkout_params["external_customer_id"] = billing.polar_customer_idif body.success_url:checkout_params["success_url"] = body.success_urlif body.embed_origin:@@ -763,7 +767,6 @@ def create_checkout(request, body: CheckoutRequest):tags=["Billing"],)def uncancel_subscription(request):- from mwmbl.quota import get_monthly_countcheck_email_verified(request)billing = getattr(request.user, "billing", None)if not billing or not billing.polar_subscription_id:@@ -778,15 +781,7 @@ def uncancel_subscription(request):billing.current_period_end = result.current_period_endbilling.cancel_at_period_end = Falsebilling.save()- usage = get_monthly_count(request.user.id)- return SubscriptionResponse(- plan=request.user.tier,- status="active",- monthly_limit=MwmblUser.TIER_MONTHLY_LIMITS[request.user.tier],- monthly_usage=usage,- current_period_end=billing.current_period_end,- polar_customer_id=billing.polar_customer_id,- )+ return _subscription_response(request.user, billing, "active")@router.post(@@ -795,11 +790,10 @@ def uncancel_subscription(request):response=SubscriptionResponse,summary="Cancel subscription at period end",description="Schedules the subscription to cancel at the end of the current billing period. "- "The plan remains active until then.",+ "The spend limit remains active until then.",tags=["Billing"],)def cancel_subscription(request):- from mwmbl.quota import get_monthly_countcheck_email_verified(request)billing = getattr(request.user, "billing", None)if not billing or not billing.polar_subscription_id:@@ -815,68 +809,49 @@ def cancel_subscription(request):billing.current_period_end = result.current_period_endbilling.cancel_at_period_end = Truebilling.save()- usage = get_monthly_count(request.user.id)- return SubscriptionResponse(- plan=request.user.tier,- status="canceling",- monthly_limit=MwmblUser.TIER_MONTHLY_LIMITS[request.user.tier],- monthly_usage=usage,- current_period_end=billing.current_period_end,- polar_customer_id=billing.polar_customer_id,- )+ return _subscription_response(request.user, billing, "canceling")@router.post(- "/billing/change-plan",+ "/billing/spend-limit",auth=JWTAuth(),response=SubscriptionResponse,- summary="Change subscription plan",- description="Upgrades or downgrades to a different paid plan. Takes effect immediately "- "with proration applied to the next invoice. The tier shown in the response "- "reflects the current state; the new tier arrives via webhook.",+ summary="Set monthly spend limit",+ description=(+ "Sets the maximum amount (in cents) the account may be billed per month "+ "for metered API usage beyond the free 2,000 requests. Set to 0 to stay "+ "free-tier-only (hard-capped at 2,000 requests/month). Requires an active "+ "Polar subscription if raising above 0 for the first time — "+ "call POST /billing/checkout first if no subscription exists."+ ),tags=["Billing"],)-def change_plan(request, body: ChangePlanRequest):- from mwmbl.quota import get_monthly_count+def update_spend_limit(request, body: UpdateSpendLimitRequest):check_email_verified(request)billing = getattr(request.user, "billing", None)- if not billing or not billing.polar_subscription_id:- raise InvalidRequest("No active subscription found.", status=404)- product_map = {- "starter": settings.POLAR_PRODUCT_ID_STARTER,- "pro": settings.POLAR_PRODUCT_ID_PRO,- }- product_id = product_map[body.plan]- if not product_id:- raise InvalidRequest(f"Plan '{body.plan}' is not configured. Contact support.", status=503)- with Polar(access_token=settings.POLAR_ACCESS_TOKEN, server=settings.POLAR_SERVER) as polar:- result = polar.subscriptions.update(- id=billing.polar_subscription_id,- subscription_update=CustomerSubscriptionUpdateProduct(product_id=product_id),+ if body.max_monthly_spend_cents > 0 and (not billing or not billing.polar_subscription_id):+ raise InvalidRequest(+ "An active billing subscription is required before raising your spend limit "+ "above $0. Call POST /billing/checkout first.",+ status=409,)- billing.current_period_end = result.current_period_end+ if billing is None:+ billing = UserBilling.objects.create(user=request.user)+ billing.max_monthly_spend_cents = body.max_monthly_spend_centsbilling.save()- usage = get_monthly_count(request.user.id)- if request.user.tier == MwmblUser.Tier.FREE:+ if billing.max_monthly_spend_cents == 0:status = "free"elif billing.cancel_at_period_end:status = "canceling"else:status = "active"- return SubscriptionResponse(- plan=request.user.tier,- status=status,- monthly_limit=MwmblUser.TIER_MONTHLY_LIMITS[request.user.tier],- monthly_usage=usage,- current_period_end=billing.current_period_end,- polar_customer_id=billing.polar_customer_id,- )+ return _subscription_response(request.user, billing, status)@router.post("/billing/webhook",summary="Polar webhook receiver",- description="Receives signed webhook events from Polar and updates the user's plan.",+ description="Receives signed webhook events from Polar and keeps the user's billing state in sync.",tags=["Billing"],)def polar_webhook(request):@@ -892,12 +867,7 @@ def polar_webhook(request):raise InvalidRequest("Invalid signature", status=400)event_type = event.TYPE- logger.info("Polar webhook event type=%s product_id=%s", event_type, getattr(event.data, "product_id", None))-- product_tier = {- settings.POLAR_PRODUCT_ID_STARTER: MwmblUser.Tier.STARTER,- settings.POLAR_PRODUCT_ID_PRO: MwmblUser.Tier.PRO,- }+ logger.info("Polar webhook event type=%s", event_type)if event_type in ("subscription.active", "subscription.updated", "subscription.uncanceled"):user_id = event.data.metadata.get("user_id")@@ -906,13 +876,6 @@ def polar_webhook(request):if user is None:logger.warning("Polar webhook: no user found for user_id=%s", user_id)else:- tier = product_tier.get(event.data.product_id, MwmblUser.Tier.FREE)- logger.info("Polar webhook: setting user %s (id=%s) tier to %s (product_id=%s)", user.email, user_id, tier, event.data.product_id)- if tier == MwmblUser.Tier.FREE:- logger.warning("Polar webhook: product_id=%s not found in product_tier map, defaulting to FREE", event.data.product_id)- user.tier = tier- user.save()- invalidate_user_api_key_cache(user.id)billing, created = UserBilling.objects.get_or_create(user=user)logger.info("Polar webhook: UserBilling %s for user %s customer_id=%s subscription_id=%s", "created" if created else "updated", user.email, event.data.customer_id, event.data.id)billing.polar_customer_id = event.data.customer_id or billing.polar_customer_id@@ -934,13 +897,11 @@ def polar_webhook(request):billing.save()logger.info("Polar webhook: user %s (id=%s) subscription scheduled to cancel at period end", user.email, user_id)else:- logger.info("Polar webhook: immediate cancellation for user %s (id=%s), reverting to FREE", user.email, user_id)- user.tier = MwmblUser.Tier.FREE- user.save()- invalidate_user_api_key_cache(user.id)+ logger.info("Polar webhook: immediate cancellation for user %s (id=%s), resetting spend limit to $0", user.email, user_id)billing = getattr(user, "billing", None)if billing:billing.cancel_at_period_end = False+ billing.max_monthly_spend_cents = 0billing.save()elif event_type == "subscription.revoked":user_id = event.data.metadata.get("user_id")@@ -949,13 +910,11 @@ def polar_webhook(request):if user is None:logger.warning("Polar webhook: no user found for user_id=%s", user_id)else:- logger.info("Polar webhook: reverting user %s (id=%s) to FREE", user.email, user_id)- user.tier = MwmblUser.Tier.FREE- user.save()- invalidate_user_api_key_cache(user.id)+ logger.info("Polar webhook: resetting user %s (id=%s) spend limit to $0", user.email, user_id)billing = getattr(user, "billing", None)if billing:billing.cancel_at_period_end = False+ billing.max_monthly_spend_cents = 0billing.save()else:logger.info("Polar webhook: unhandled event type=%s, ignoring", event_type)diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.pyindex cd81ee9..c7efcc3 100644--- a/mwmbl/platform/schemas.py+++ b/mwmbl/platform/schemas.py@@ -13,28 +13,28 @@ class UserProfileResponse(Schema):class SubscriptionResponse(Schema):- plan: strstatus: str+ max_monthly_spend_cents: intmonthly_limit: intmonthly_usage: int+ estimated_cost_cents: intcurrent_period_end: Optional[datetime]polar_customer_id: Optional[str]class CheckoutRequest(Schema):- plan: Literal["starter", "pro"]success_url: Optional[str] = Noneembed_origin: Optional[str] = None-class ChangePlanRequest(Schema):- plan: Literal["starter", "pro"]--class CheckoutResponse(Schema):checkout_url: str+class UpdateSpendLimitRequest(Schema):+ max_monthly_spend_cents: int = Field(ge=0)++class ForgotPasswordRequest(Schema):email: strdiff --git a/mwmbl/pricing.py b/mwmbl/pricing.pynew file mode 100644index 0000000..da208a6--- /dev/null+++ b/mwmbl/pricing.py@@ -0,0 +1,36 @@+"""Pure pricing constants and calculations for the usage-based API pricing model.++No Django/DB/cache imports — safe to import from the search hot path, the+billing endpoints, and the background usage-reporting job without risk of+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++# 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:+ """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+ drift from fractional-cent-per-request division.+ """+ if max_monthly_spend_cents <= 0:+ return FREE_KEYED_MONTHLY_LIMIT+ paid_requests = (max_monthly_spend_cents * 1000) // PRICE_PER_1000_QUERIES_CENTS+ return FREE_KEYED_MONTHLY_LIMIT + paid_requests+++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:+ """Estimated cost in cents for the current month's usage, rounded down."""+ return (billable_overage(monthly_count) * PRICE_PER_1000_QUERIES_CENTS) // 1000diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex b13d15e..23cea12 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -267,8 +267,7 @@ RUST_MODEL_PATH = Path(__file__).parent / 'resources' / "model.xgb"POLAR_ACCESS_TOKEN = os.environ.get("POLAR_ACCESS_TOKEN", "")POLAR_WEBHOOK_SECRET = os.environ.get("POLAR_WEBHOOK_SECRET", "")-POLAR_PRODUCT_ID_STARTER = os.environ.get("POLAR_PRODUCT_ID_STARTER", "")-POLAR_PRODUCT_ID_PRO = os.environ.get("POLAR_PRODUCT_ID_PRO", "")+POLAR_PRODUCT_ID_USAGE = os.environ.get("POLAR_PRODUCT_ID_USAGE", "")POLAR_SERVER = os.environ.get("POLAR_SERVER", "sandbox")GUARDIAN_API_KEY = os.environ.get("GUARDIAN_API_KEY", "")diff --git a/mwmbl/tinysearchengine/search.py b/mwmbl/tinysearchengine/search.pyindex c26d34d..fdcc624 100644--- a/mwmbl/tinysearchengine/search.py+++ b/mwmbl/tinysearchengine/search.py@@ -5,6 +5,7 @@ from typing import Optionalfrom ninja import NinjaAPI, Router, Schemafrom ninja.errors import HttpError+from mwmbl import pricingfrom mwmbl.format import format_result, format_result_v2from mwmbl.models import ApiKey, MwmblUserfrom mwmbl.quota import check_rate_limit, get_monthly_count, increment_monthly@@ -194,15 +195,16 @@ _COMPLETE_RESPONSE_SCHEMA = {# Upgrade message helper# ----------------------------------------------------------------------------def _upgrade_message(tier: str) -> str:- if tier == MwmblUser.Tier.FREE:+def _upgrade_message(max_monthly_spend_cents: int) -> str:+ if max_monthly_spend_cents <= 0:return (- "Upgrade to Starter (10,000 requests/month) or Pro (50,000 requests/month) "- "at https://mwmbl.org/pricing."+ "Increase your monthly spend limit at https://mwmbl.org/pricing to continue "+ "past the free 2,000 requests/month (billed at $5.00 per 1,000 additional queries).")- if tier == MwmblUser.Tier.STARTER:- return "Upgrade to Pro (50,000 requests/month) at https://mwmbl.org/pricing."- return "" # Pro — no upgrade available+ return (+ "Increase your monthly spend limit at https://mwmbl.org/pricing to allow more "+ "requests this month."+ )# ---------------------------------------------------------------------------@@ -297,7 +299,9 @@ def _register_search_v2(r: Router | NinjaAPI, ranker: HeuristicRanker):if api_key is not None:user: MwmblUser = api_key.user- monthly_limit = MwmblUser.TIER_MONTHLY_LIMITS[user.tier]+ 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)if not check_rate_limit(user.id):raise HttpError(@@ -307,13 +311,11 @@ def _register_search_v2(r: Router | NinjaAPI, ranker: HeuristicRanker):current_count = get_monthly_count(user.id)if current_count >= monthly_limit:- upgrade_msg = _upgrade_message(user.tier)msg = (- f"Monthly quota exceeded: your {user.get_tier_display()} plan allows "- f"{monthly_limit:,} requests per month and you have used {current_count:,}."+ f"Monthly quota exceeded: your account allows {monthly_limit:,} requests "+ f"per month at your current spend limit and you have used {current_count:,}. "+ f"{_upgrade_message(spend_cents)}")- if upgrade_msg:- msg += f" {upgrade_msg}"raise HttpError(429, msg)monthly_usage = increment_monthly(user.id)diff --git a/test/test_background_polar_reporting.py b/test/test_background_polar_reporting.pynew file mode 100644index 0000000..764548b--- /dev/null+++ b/test/test_background_polar_reporting.py@@ -0,0 +1,118 @@+"""+Tests for the report_usage_to_polar background task.++Covers incremental-delta ingestion, skipping users with no linked Polar+customer, and no-op behavior below the free allowance.+"""++from datetime import datetime, timezone+from unittest.mock import patch++import pytest+from allauth.account.models import EmailAddress+from django.contrib.auth import get_user_model++from mwmbl import pricing+from mwmbl.background import report_usage_to_polar+from mwmbl.models import UsageBucket, UserBilling++User = get_user_model()+++def billed_user(db):+ user = User.objects.create_user(+ username="billeduser", email="[email protected]", password="testpass123",+ )+ EmailAddress.objects.create(user=user, email="[email protected]", verified=True, primary=True)+ UserBilling.objects.create(+ user=user,+ polar_customer_id="cust_test123",+ polar_subscription_id="sub_test123",+ max_monthly_spend_cents=10_000,+ )+ return user+++def test_report_usage_to_polar_ingests_delta_only(billed_user):+ 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=0,+ )++ with patch("polar_sdk.Polar") as MockPolar:+ mock_polar_instance = MockPolar.return_value.__enter__.return_value+ report_usage_to_polar.now()++ mock_polar_instance.events.ingest.assert_called_once()+ call_kwargs = mock_polar_instance.events.ingest.call_args[1]+ events = call_kwargs["request"]["events"]+ assert len(events) == 1+ assert events[0]["external_customer_id"] == str(billed_user.id)+ assert events[0]["metadata"]["quantity"] == 500++ bucket.refresh_from_db()+ assert bucket.reported_overage == 500+++def test_report_usage_to_polar_skips_users_without_polar_customer(db):+ user = User.objects.create_user(+ username="nocustomer", email="[email protected]", password="testpass123",+ )+ EmailAddress.objects.create(user=user, email="[email protected]", verified=True, primary=True)+ now = datetime.now(timezone.utc)+ UsageBucket.objects.create(+ user=user, year=now.year, month=now.month,+ count=pricing.FREE_KEYED_MONTHLY_LIMIT + 500, reported_overage=0,+ )++ with patch("polar_sdk.Polar") as MockPolar:+ mock_polar_instance = MockPolar.return_value.__enter__.return_value+ report_usage_to_polar.now()++ mock_polar_instance.events.ingest.assert_not_called()+++def test_report_usage_to_polar_no_op_below_free_allowance(billed_user):+ now = datetime.now(timezone.utc)+ bucket = UsageBucket.objects.create(+ user=billed_user, year=now.year, month=now.month,+ count=pricing.FREE_KEYED_MONTHLY_LIMIT - 1, reported_overage=0,+ )++ with patch("polar_sdk.Polar") as MockPolar:+ mock_polar_instance = MockPolar.return_value.__enter__.return_value+ report_usage_to_polar.now()++ mock_polar_instance.events.ingest.assert_not_called()+ bucket.refresh_from_db()+ assert bucket.reported_overage == 0+++def test_report_usage_to_polar_incremental_second_run(billed_user):+ 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=500,+ )++ # More usage has accumulated since the last report.+ bucket.count = pricing.FREE_KEYED_MONTHLY_LIMIT + 800+ bucket.save()++ with patch("polar_sdk.Polar") as MockPolar:+ mock_polar_instance = MockPolar.return_value.__enter__.return_value+ report_usage_to_polar.now()++ call_kwargs = mock_polar_instance.events.ingest.call_args[1]+ events = call_kwargs["request"]["events"]+ assert len(events) == 1+ assert events[0]["metadata"]["quantity"] == 300 # only the new delta++ bucket.refresh_from_db()+ assert bucket.reported_overage == 800diff --git a/test/test_platform_billing.py b/test/test_platform_billing.pyindex bc8cecc..afbb88d 100644--- a/test/test_platform_billing.py+++ b/test/test_platform_billing.py@@ -4,7 +4,9 @@ Tests for platform billing endpoints.Covers:- POST /api/v1/platform/billing/cancel- POST /api/v1/platform/billing/uncancel-- POST /api/v1/platform/billing/change-plan+- POST /api/v1/platform/billing/spend-limit+- POST /api/v1/platform/billing/checkout+- POST /api/v1/platform/billing/webhook"""from unittest.mock import patch@@ -15,7 +17,7 @@ from django.contrib.auth import get_user_modelfrom django.test import Clientfrom ninja_jwt.tokens import RefreshToken-from mwmbl.models import AgreementType, MwmblUser, UserAgreement, UserBilling+from mwmbl.models import AgreementType, UserAgreement, UserBillingUser = get_user_model()@@ -47,9 +49,8 @@ def verified_user_with_billing(db):polar_subscription_id="sub_test123",current_period_end=None,cancel_at_period_end=False,+ max_monthly_spend_cents=1_000,)- user.tier = MwmblUser.Tier.STARTER- user.save()return user@@ -217,78 +218,205 @@ def test_uncancel_subscription_unauthenticated(api_client):# ----------------------------------------------------------------------------# Change plan tests+# Spend limit tests# ---------------------------------------------------------------------------@pytest.mark.django_db-def test_change_plan_success(api_client, access_token, verified_user_with_billing):- """Test successful plan change."""- from django.conf import settings+def test_update_spend_limit_requires_subscription_first(api_client, access_token, db):+ """Raising the spend limit above $0 without an active subscription returns 409."""+ user = User.objects.create_user(+ username="nobilling", email="[email protected]", password="testpass123",+ )+ EmailAddress.objects.create(user=user, email="[email protected]", verified=True, primary=True)+ token = str(RefreshToken.for_user(user).access_token)- with patch.object(settings, "POLAR_PRODUCT_ID_PRO", "prod_test123"), \- patch("mwmbl.platform.api.Polar") as MockPolar:- mock_polar_instance = MockPolar.return_value.__enter__.return_value- mock_result = mock_polar_instance.subscriptions.update.return_value- mock_result.current_period_end = None+ response = api_client.post(+ "/api/v1/platform/billing/spend-limit",+ content_type="application/json",+ data={"max_monthly_spend_cents": 1_000},+ **auth_headers(token),+ )- response = api_client.post(- "/api/v1/platform/billing/change-plan",- content_type="application/json",- data={"plan": "pro"},- **auth_headers(access_token),- )+ assert response.status_code == 409+++def test_update_spend_limit_success(api_client, access_token, verified_user_with_billing):+ """Raising the spend limit with an active subscription succeeds."""+ response = api_client.post(+ "/api/v1/platform/billing/spend-limit",+ content_type="application/json",+ data={"max_monthly_spend_cents": 2_500},+ **auth_headers(access_token),+ )assert response.status_code == 200data = response.json()+ assert data["max_monthly_spend_cents"] == 2_500assert data["status"] == "active"- assert data["plan"] == MwmblUser.Tier.STARTER- mock_polar_instance.subscriptions.update.assert_called_once()- call_kwargs = mock_polar_instance.subscriptions.update.call_args[1]- subscription_update = call_kwargs["subscription_update"]- assert hasattr(subscription_update, "product_id")+ billing = UserBilling.objects.get(user=verified_user_with_billing)+ assert billing.max_monthly_spend_cents == 2_500@pytest.mark.django_db-def test_change_plan_unauthenticated(api_client):- """Test that changing plan without authentication returns 401."""+def test_update_spend_limit_reset_to_zero_always_allowed(api_client, access_token, verified_user_with_billing):+ """Lowering the spend limit to 0 doesn't require any subscription check."""response = api_client.post(- "/api/v1/platform/billing/change-plan",+ "/api/v1/platform/billing/spend-limit",content_type="application/json",- data={"plan": "pro"},+ data={"max_monthly_spend_cents": 0},+ **auth_headers(access_token),)- assert response.status_code == 401++ assert response.status_code == 200+ data = response.json()+ assert data["max_monthly_spend_cents"] == 0+ assert data["status"] == "free"@pytest.mark.django_db-def test_change_plan_invalid_plan(api_client, access_token, verified_user_with_billing):- """Test that changing to an invalid plan returns 400."""+def test_update_spend_limit_unauthenticated(api_client):response = api_client.post(- "/api/v1/platform/billing/change-plan",+ "/api/v1/platform/billing/spend-limit",content_type="application/json",- data={"plan": "invalid"},- **auth_headers(access_token),+ data={"max_monthly_spend_cents": 1_000},)+ assert response.status_code == 401- assert response.status_code == 422++# ---------------------------------------------------------------------------+# Checkout tests+# ---------------------------------------------------------------------------@pytest.mark.django_db-def test_change_plan_no_subscription(api_client, access_token, verified_user_with_billing):- """Test that changing plan without a subscription returns 404."""+def test_checkout_uses_single_usage_product(api_client, access_token, verified_user_with_billing):+ """Checkout always targets the single usage product and always sets external_customer_id."""+ from django.conf import settings++ with patch.object(settings, "POLAR_PRODUCT_ID_USAGE", "prod_usage123"), \+ patch("mwmbl.platform.api.Polar") as MockPolar:+ mock_polar_instance = MockPolar.return_value.__enter__.return_value+ mock_polar_instance.checkouts.create.return_value.url = "https://polar.example/checkout/abc"++ response = api_client.post(+ "/api/v1/platform/billing/checkout",+ content_type="application/json",+ data={},+ **auth_headers(access_token),+ )++ assert response.status_code == 200+ assert response.json()["checkout_url"] == "https://polar.example/checkout/abc"++ call_kwargs = mock_polar_instance.checkouts.create.call_args[1]+ checkout_params = call_kwargs["request"]+ assert checkout_params["products"] == ["prod_usage123"]+ assert checkout_params["external_customer_id"] == str(verified_user_with_billing.id)+++def test_checkout_not_configured_returns_503(api_client, access_token, verified_user_with_billing):+ from django.conf import settings++ with patch.object(settings, "POLAR_PRODUCT_ID_USAGE", ""):+ response = api_client.post(+ "/api/v1/platform/billing/checkout",+ content_type="application/json",+ data={},+ **auth_headers(access_token),+ )++ assert response.status_code == 503+++# ---------------------------------------------------------------------------+# Webhook tests+# ---------------------------------------------------------------------------+++def _mock_webhook_event(event_type, user_id, **data_overrides):+ from unittest.mock import Mock+ event = Mock()+ event.TYPE = event_type+ event.data = Mock()+ event.data.metadata = {"user_id": str(user_id)}+ event.data.customer_id = data_overrides.get("customer_id", "cust_new")+ event.data.id = data_overrides.get("subscription_id", "sub_new")+ event.data.current_period_end = data_overrides.get("current_period_end", None)+ event.data.cancel_at_period_end = data_overrides.get("cancel_at_period_end", False)+ return event+++def test_webhook_subscription_active_sets_billing_fields_not_spend_limit(api_client, verified_user_with_billing):billing = UserBilling.objects.get(user=verified_user_with_billing)- billing.polar_subscription_id = ""+ billing.max_monthly_spend_cents = 2_500billing.save()- response = api_client.post(- "/api/v1/platform/billing/change-plan",- content_type="application/json",- data={"plan": "pro"},- **auth_headers(access_token),- )+ event = _mock_webhook_event("subscription.active", verified_user_with_billing.id, customer_id="cust_abc", subscription_id="sub_abc")+ with patch("mwmbl.platform.api.validate_event", return_value=event):+ response = api_client.post(+ "/api/v1/platform/billing/webhook",+ content_type="application/json",+ data={},+ )- assert response.status_code == 404- data = response.json()- assert data["status"] == "error"- assert "no active subscription" in data["message"].lower()+ assert response.status_code == 200+ billing.refresh_from_db()+ assert billing.polar_customer_id == "cust_abc"+ assert billing.polar_subscription_id == "sub_abc"+ # Spend limit is untouched by subscription state changes.+ assert billing.max_monthly_spend_cents == 2_500+++def test_webhook_subscription_canceled_immediate_resets_spend_limit_to_zero(api_client, verified_user_with_billing):+ billing = UserBilling.objects.get(user=verified_user_with_billing)+ assert billing.max_monthly_spend_cents == 1_000++ event = _mock_webhook_event("subscription.canceled", verified_user_with_billing.id, cancel_at_period_end=False)+ with patch("mwmbl.platform.api.validate_event", return_value=event):+ response = api_client.post(+ "/api/v1/platform/billing/webhook",+ content_type="application/json",+ data={},+ )++ assert response.status_code == 200+ billing.refresh_from_db()+ assert billing.max_monthly_spend_cents == 0+ assert billing.cancel_at_period_end is False+++def test_webhook_subscription_canceled_scheduled_does_not_reset_spend_limit(api_client, verified_user_with_billing):+ event = _mock_webhook_event("subscription.canceled", verified_user_with_billing.id, cancel_at_period_end=True)+ with patch("mwmbl.platform.api.validate_event", return_value=event):+ response = api_client.post(+ "/api/v1/platform/billing/webhook",+ content_type="application/json",+ data={},+ )++ assert response.status_code == 200+ billing = UserBilling.objects.get(user=verified_user_with_billing)+ assert billing.max_monthly_spend_cents == 1_000+ assert billing.cancel_at_period_end is True+++def test_webhook_subscription_revoked_resets_spend_limit_to_zero(api_client, verified_user_with_billing):+ event = _mock_webhook_event("subscription.revoked", verified_user_with_billing.id)+ with patch("mwmbl.platform.api.validate_event", return_value=event):+ response = api_client.post(+ "/api/v1/platform/billing/webhook",+ content_type="application/json",+ data={},+ )++ assert response.status_code == 200+ billing = UserBilling.objects.get(user=verified_user_with_billing)+ assert billing.max_monthly_spend_cents == 0diff --git a/test/test_pricing.py b/test/test_pricing.pynew file mode 100644index 0000000..8fe7b92--- /dev/null+++ b/test/test_pricing.py@@ -0,0 +1,48 @@+"""Unit tests for mwmbl.pricing — pure boundary-value checks, no DB/Django needed."""++from mwmbl import pricing+++def test_effective_monthly_request_cap_zero_spend_is_free_allowance():+ assert pricing.effective_monthly_request_cap(0) == pricing.FREE_KEYED_MONTHLY_LIMIT+++def test_effective_monthly_request_cap_negative_spend_is_free_allowance():+ assert pricing.effective_monthly_request_cap(-100) == pricing.FREE_KEYED_MONTHLY_LIMIT+++def test_effective_monthly_request_cap_ten_dollars():+ # $10 = 1000 cents -> 2000 extra requests at $5/1000+ assert pricing.effective_monthly_request_cap(1_000) == 2_000 + 2_000+++def test_effective_monthly_request_cap_twenty_five_dollars():+ assert pricing.effective_monthly_request_cap(2_500) == 2_000 + 5_000+++def test_effective_monthly_request_cap_hundred_dollars():+ assert pricing.effective_monthly_request_cap(10_000) == 2_000 + 20_000+++def test_effective_monthly_request_cap_arbitrary_cents():+ # At $5.00/1000 requests, every cent buys exactly 2 requests (integer ratio).+ assert pricing.effective_monthly_request_cap(750) == 2_000 + 1_500+ assert pricing.effective_monthly_request_cap(751) == 2_000 + 1_502+++def test_billable_overage_below_free_allowance_is_zero():+ assert pricing.billable_overage(0) == 0+ assert pricing.billable_overage(pricing.FREE_KEYED_MONTHLY_LIMIT) == 0+++def test_billable_overage_above_free_allowance():+ assert pricing.billable_overage(pricing.FREE_KEYED_MONTHLY_LIMIT + 500) == 500+++def test_estimated_cost_cents_below_free_allowance_is_zero():+ assert pricing.estimated_cost_cents(pricing.FREE_KEYED_MONTHLY_LIMIT) == 0+++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) == 250diff --git a/test/test_search_api_key.py b/test/test_search_api_key.pyindex 052f3f5..bf14531 100644--- a/test/test_search_api_key.py+++ b/test/test_search_api_key.py@@ -22,8 +22,9 @@ from ninja_jwt.tokens import RefreshTokenfrom django.conf import settings+from mwmbl import pricingfrom mwmbl.background import sync_search_counts-from mwmbl.models import ApiKey, AgreementType, MwmblUser, UsageBucket, UserAgreement, generate_api_key+from mwmbl.models import ApiKey, AgreementType, MwmblUser, UsageBucket, UserAgreement, UserBilling, generate_api_keyfrom mwmbl.quota import RATE_LIMIT, _monthly_key, check_rate_limit, get_monthly_count, increment_monthlyUser = get_user_model()@@ -371,7 +372,7 @@ def test_search_response_includes_usage_fields(api_client, search_api_key):data = response.json()assert "monthly_usage" in dataassert "monthly_limit" in data- assert data["monthly_limit"] == MwmblUser.TIER_MONTHLY_LIMITS[MwmblUser.Tier.FREE]+ assert data["monthly_limit"] == pricing.FREE_KEYED_MONTHLY_LIMIT# ---------------------------------------------------------------------------@@ -391,7 +392,7 @@ def test_search_rate_limit_exceeded(api_client, search_api_key):@pytest.mark.django_dbdef test_search_monthly_quota_exceeded(api_client, search_api_key):- limit = MwmblUser.TIER_MONTHLY_LIMITS[MwmblUser.Tier.FREE]+ limit = pricing.FREE_KEYED_MONTHLY_LIMITwith patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=True), \patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=limit):response = api_client.get(@@ -401,25 +402,45 @@ def test_search_monthly_quota_exceeded(api_client, search_api_key):assert response.status_code == 429detail = response.json()["detail"]assert "quota" in detail.lower() or "monthly" in detail.lower()- # Free tier should mention upgrade options- assert "starter" in detail.lower() or "pro" in detail.lower() or "upgrade" in detail.lower()+ assert "spend limit" in detail.lower()@pytest.mark.django_db-def test_search_monthly_quota_exceeded_pro_no_upgrade_message(api_client, search_api_key, verified_user):- """Pro tier 429 message should not suggest an upgrade."""- verified_user.tier = MwmblUser.Tier.PRO- verified_user.save()- limit = MwmblUser.TIER_MONTHLY_LIMITS[MwmblUser.Tier.PRO]+def test_search_keyed_default_zero_spend_cap_is_free_allowance(api_client, search_api_key):+ """A fresh account with no UserBilling row defaults to the free-only cap."""with patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=True), \- patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=limit):+ patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=pricing.FREE_KEYED_MONTHLY_LIMIT - 1), \+ patch("mwmbl.tinysearchengine.search.increment_monthly", return_value=pricing.FREE_KEYED_MONTHLY_LIMIT):+ response = api_client.get(+ "/api/v2/search/?q=python",+ **api_key_header(search_api_key.raw_key),+ )+ assert response.status_code == 200+ assert response.json()["monthly_limit"] == pricing.FREE_KEYED_MONTHLY_LIMIT+++def test_search_keyed_with_spend_limit_raises_cap(api_client, search_api_key, verified_user):+ """Raising the configured spend limit raises the effective monthly request cap."""+ UserBilling.objects.create(user=verified_user, max_monthly_spend_cents=1_000)+ cap = pricing.effective_monthly_request_cap(1_000)+ assert cap == pricing.FREE_KEYED_MONTHLY_LIMIT + 2_000++ with patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=True), \+ patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=cap - 1):+ response = api_client.get(+ "/api/v2/search/?q=python",+ **api_key_header(search_api_key.raw_key),+ )+ assert response.status_code == 200++ with patch("mwmbl.tinysearchengine.search.check_rate_limit", return_value=True), \+ patch("mwmbl.tinysearchengine.search.get_monthly_count", return_value=cap):response = api_client.get("/api/v2/search/?q=python",**api_key_header(search_api_key.raw_key),)assert response.status_code == 429- detail = response.json()["detail"]- assert "upgrade" not in detail.lower()# ---------------------------------------------------------------------------@@ -636,10 +657,11 @@ def test_subscription_free_user_no_usage(api_client, access_token, verified_user)assert response.status_code == 200data = response.json()- assert data["plan"] == MwmblUser.Tier.FREEassert data["status"] == "free"- assert data["monthly_limit"] == MwmblUser.TIER_MONTHLY_LIMITS[MwmblUser.Tier.FREE]+ assert data["max_monthly_spend_cents"] == 0+ assert data["monthly_limit"] == pricing.FREE_KEYED_MONTHLY_LIMITassert data["monthly_usage"] == 0+ assert data["estimated_cost_cents"] == 0assert data["current_period_end"] is Noneassert data["polar_customer_id"] is None@@ -689,9 +711,8 @@ def test_subscription_usage_matches_search_response(api_client, access_token, ve@pytest.mark.django_db-def test_subscription_correct_limit_for_starter_tier(api_client, access_token, verified_user):- verified_user.tier = MwmblUser.Tier.STARTER- verified_user.save()+def test_subscription_reflects_spend_limit(api_client, access_token, verified_user):+ UserBilling.objects.create(user=verified_user, max_monthly_spend_cents=1_000)response = api_client.get("/api/v1/platform/billing/subscription",@@ -699,9 +720,9 @@ def test_subscription_correct_limit_for_starter_tier(api_client, access_token, v)assert response.status_code == 200data = response.json()- assert data["plan"] == MwmblUser.Tier.STARTERassert data["status"] == "active"- assert data["monthly_limit"] == MwmblUser.TIER_MONTHLY_LIMITS[MwmblUser.Tier.STARTER]+ assert data["max_monthly_spend_cents"] == 1_000+ assert data["monthly_limit"] == pricing.effective_monthly_request_cap(1_000)# ---------------------------------------------------------------------------