An open source, non-profit web search engine
Make the volunteer membership its own Pollinator tier
Claude7130bf648414
diff --git a/mwmbl/admin.py b/mwmbl/admin.pyindex 10f3e6c..9ec5eb5 100644--- a/mwmbl/admin.py+++ b/mwmbl/admin.py@@ -5,7 +5,6 @@ from django.contrib.auth.admin import UserAdminfrom mwmbl.models import (ApiKey,- CrawlerMembership,Curation,DomainSubmission,FlagCuration,@@ -14,6 +13,7 @@ from mwmbl.models import (MwmblUser,OldIndex,UserBilling,+ VolunteerMembership,generate_api_key,)@@ -97,13 +97,14 @@ class MembershipAdmin(ModelAdmin):admin.site.register(Membership, MembershipAdmin)-class CrawlerMembershipAdmin(ModelAdmin):- list_display = ("user", "valid_until", "started")+class VolunteerMembershipAdmin(ModelAdmin):+ list_display = ("user", "tier", "valid_until", "started")+ list_filter = ("tier",)readonly_fields = ("started",)search_fields = ("user__username", "user__email")-admin.site.register(CrawlerMembership, CrawlerMembershipAdmin)+admin.site.register(VolunteerMembership, VolunteerMembershipAdmin)# Adds the "Status" panel linking to the blacklist status page (mwmbl.admin_views) to the# admin front page.diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.pyindex 0c09b54..7aa5102 100644--- a/mwmbl/admin_views.py+++ b/mwmbl/admin_views.py@@ -45,8 +45,8 @@ from mwmbl.indexer.blacklist_snapshot import (get_snapshot_blacklist,)from mwmbl.indexer.purge_queue import MAX_QUEUE_SIZE, PURGE_QUEUE_KEY, peek_purge_queue-from mwmbl.membership import TIERS, MembershipTier, combined_search_monthly_limit-from mwmbl.models import ApiKey, CrawlerMembership, Membership, MwmblUser+from mwmbl.membership import TIERS, VOLUNTEER_TIERS, combined_search_monthly_limit+from mwmbl.models import ApiKey, Membership, MwmblUserfrom mwmbl.traffic import (HEADER_LABELS,STATUS_LABELS,@@ -57,6 +57,7 @@ from mwmbl.traffic import (read_user_agent_counts,)from mwmbl.utils import utc_today+from mwmbl.volunteer_membership import current_volunteer_membershipslogger = getLogger(__name__)@@ -409,25 +410,29 @@ def _seed_search_stats() -> dict:"""This month's Seed Search (Combined Search) usage by signed-in users, by tier.Combined Search refuses API keys, so every counter belongs to a signed-in web user.- "free" is everyone without a membership, matching COMBINED_SEARCH_MONTHLY_LIMITS.+ "free" is everyone without a membership, matching COMBINED_SEARCH_MONTHLY_LIMITS. A user+ with both a paid and a volunteer tier is counted under whichever sets their limit."""counts = quota.get_all_monthly_combined_search_counts()users_by_id = MwmblUser.objects.in_bulk(list(counts))# Counters outlive deleted accounts until they expire, so skip users that no longer exist.counts = {user_id: count for user_id, count in counts.items() if user_id in users_by_id}- tier_by_user = {- user_id: MembershipTier.SPROUT.value- for user_id in CrawlerMembership.objects.filter(user_id__in=counts, valid_until__gte=utc_today()).values_list(- "user_id", flat=True- )+ paid_tier_by_user = dict(Membership.objects.filter(user_id__in=counts).values_list("user_id", "tier"))+ volunteer_tier_by_user = {+ user_id: volunteer_membership.tier+ for user_id, volunteer_membership in current_volunteer_memberships(list(counts)).items()}- tier_by_user |= dict(Membership.objects.filter(user_id__in=counts).values_list("user_id", "tier"))- tier_names = ["free"] + [tier_info.tier.value for tier_info in TIERS]+ tier_names = (+ ["free"]+ + [tier_info.tier.value for tier_info in TIERS]+ + [tier_info.tier.value for tier_info in VOLUNTEER_TIERS]+ )by_tier = {tier: {"tier": tier, "users": 0, "queries": 0, "at_limit": 0} for tier in tier_names}rows = []for user_id, count in counts.items():- tier = tier_by_user.get(user_id, "free")+ held = [tier for tier in (paid_tier_by_user.get(user_id), volunteer_tier_by_user.get(user_id)) if tier]+ tier = max(held, key=combined_search_monthly_limit, default="free")limit = combined_search_monthly_limit(tier)tier_stats = by_tier[tier]tier_stats["users"] += 1diff --git a/mwmbl/crawler/stats.py b/mwmbl/crawler/stats.pyindex 4b555c1..34262fc 100644--- a/mwmbl/crawler/stats.py+++ b/mwmbl/crawler/stats.py@@ -10,9 +10,9 @@ from redis import Redisfrom mwmbl.count_urls import get_counts, get_domain_result_countfrom mwmbl.crawler.batch import Results-from mwmbl.crawler_membership import update_crawler_membershipfrom mwmbl.models import MwmblUser, UserStatsfrom mwmbl.utils import utc_today+from mwmbl.volunteer_membership import update_volunteer_membershipslogger = getLogger(__name__)@@ -225,7 +225,7 @@ class StatsManager:num_results=num_results,)- update_crawler_membership(user, today)+ update_volunteer_memberships(user, today)def record_blacklisted_removed(self, num_results: int) -> None:"""Record documents removed from the index by the background blacklist purge.diff --git a/mwmbl/crawler_membership.py b/mwmbl/crawler_membership.pydeleted file mode 100644index cc72e38..0000000--- a/mwmbl/crawler_membership.py+++ /dev/null@@ -1,56 +0,0 @@-"""Free Sprout memberships for volunteers who crawl, and the tier a user gets from either kind of membership."""--import calendar-from datetime import date--from django.conf import settings--from mwmbl.membership import MembershipTier-from mwmbl.models import CrawlerMembership, Membership, MwmblUser, UserStats-from mwmbl.utils import utc_today---def end_of_next_month(day: date) -> date:- year, month = (day.year + 1, 1) if day.month == 12 else (day.year, day.month + 1)- return date(year, month, calendar.monthrange(year, month)[1])---def update_crawler_membership(user: MwmblUser, today: date) -> None:- """Grant or extend the user's crawler membership if they have crawled on enough days this month.-- Called after every batch of results, so the membership starts the moment the user reaches the- threshold, and a grant that failed is retried on their next batch. Once this month has earned- the membership, it costs one query. A grant never shortens a membership, so a longer one set by- hand in the admin survives.- """- valid_until = end_of_next_month(today)- if CrawlerMembership.objects.filter(user=user, valid_until__gte=valid_until).exists():- return-- days_crawled = UserStats.objects.filter(- user=user,- date__gte=today.replace(day=1),- date__lte=today,- num_results__gte=settings.CRAWLER_MEMBERSHIP_MIN_RESULTS,- ).count()- if days_crawled < settings.CRAWLER_MEMBERSHIP_DAYS:- return-- _, created = CrawlerMembership.objects.get_or_create(user=user, defaults={"valid_until": valid_until})- if not created:- CrawlerMembership.objects.filter(user=user, valid_until__lt=valid_until).update(valid_until=valid_until)---def has_crawler_membership(user_id: int) -> bool:- return CrawlerMembership.objects.filter(user_id=user_id, valid_until__gte=utc_today()).exists()---def membership_tier(user_id: int) -> str | None:- """The user's tier: their paid one if they have it, Sprout if they've earned it by crawling, else None.-- Every paid tier includes everything in Sprout, so a paid membership always wins.- """- paid_tier = Membership.objects.filter(user_id=user_id).values_list("tier", flat=True).first()- if paid_tier is not None:- return paid_tier- return MembershipTier.SPROUT.value if has_crawler_membership(user_id) else Nonediff --git a/mwmbl/membership.py b/mwmbl/membership.pyindex bb59848..2f873f7 100644--- a/mwmbl/membership.py+++ b/mwmbl/membership.py@@ -48,6 +48,36 @@ TIERS = []+class VolunteerTier(models.TextChoices):+ """Tiers earned by volunteering rather than bought. Kept apart from MembershipTier, which is sold through Polar."""++ POLLINATOR = "pollinator", "Pollinator"+++@dataclass(frozen=True)+class VolunteerTierInfo:+ tier: VolunteerTier+ # Earned by crawling on days_per_month days of a calendar month, where a day counts once+ # the user has submitted min_results_per_day results that day.+ days_per_month: int+ min_results_per_day: int+ perks: list[str]+++# Lowest first: a user holding several has the last one listed.+VOLUNTEER_TIERS = [+ VolunteerTierInfo(+ tier=VolunteerTier.POLLINATOR,+ days_per_month=3,+ min_results_per_day=100,+ perks=[+ "Access to the members area in Matrix and Discord",+ "300 Seed Search queries a month to enhance our index",+ ],+ ),+]++def product_ids() -> dict[MembershipTier, str]:return {MembershipTier.SPROUT: settings.POLAR_PRODUCT_ID_SPROUT,@@ -63,5 +93,5 @@ def tier_for_product(product_id: str) -> MembershipTier | None:def combined_search_monthly_limit(tier: str | None) -> int:- """Combined Search queries a month for a web (JWT) caller with this membership tier."""+ """Combined Search queries a month for a web (JWT) caller with this membership or volunteer tier."""return settings.COMBINED_SEARCH_MONTHLY_LIMITS[tier or "free"]diff --git a/mwmbl/migrations/0045_crawlermembership.py b/mwmbl/migrations/0045_volunteermembership.pysimilarity index 70%rename from mwmbl/migrations/0045_crawlermembership.pyrename to mwmbl/migrations/0045_volunteermembership.pyindex 8945870..2af99d2 100644--- a/mwmbl/migrations/0045_crawlermembership.py+++ b/mwmbl/migrations/0045_volunteermembership.py@@ -10,19 +10,23 @@ class Migration(migrations.Migration):operations = [migrations.CreateModel(- name="CrawlerMembership",+ name="VolunteerMembership",fields=[("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),+ ("tier", models.CharField(choices=[("pollinator", "Pollinator")], max_length=20)),("valid_until", models.DateField()),("started", models.DateTimeField(auto_now_add=True)),("user",- models.OneToOneField(+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,- related_name="crawler_membership",+ related_name="volunteer_memberships",to=settings.AUTH_USER_MODEL,),),],+ options={+ "unique_together": {("user", "tier")},+ },),]diff --git a/mwmbl/models.py b/mwmbl/models.pyindex f1603ba..a1ea47c 100644--- a/mwmbl/models.py+++ b/mwmbl/models.py@@ -6,7 +6,7 @@ from django.contrib.postgres.fields import ArrayFieldfrom django.db import modelsfrom django.utils import timezone-from mwmbl.membership import MembershipTier+from mwmbl.membership import MembershipTier, VolunteerTierfrom mwmbl.utils import bare_host@@ -269,17 +269,22 @@ class Membership(models.Model):started = models.DateTimeField(auto_now_add=True)-class CrawlerMembership(models.Model):- """A free Sprout membership earned by crawling, kept apart from Membership so Polar syncs never touch it.+class VolunteerMembership(models.Model):+ """A volunteer tier earned by crawling, kept apart from Membership so Polar syncs never touch it.- Earned on the user's CRAWLER_MEMBERSHIP_DAYS-th crawl day of a calendar month and valid to the- end of the following month, so a volunteer who keeps qualifying is never without it.+ One row per tier the user has earned, each valid to the end of the month after the one it was+ last earned in, so a volunteer who keeps qualifying is never without it. See+ mwmbl.membership.VOLUNTEER_TIERS for what earns each tier."""- user = models.OneToOneField(MwmblUser, on_delete=models.CASCADE, related_name="crawler_membership")+ user = models.ForeignKey(MwmblUser, on_delete=models.CASCADE, related_name="volunteer_memberships")+ tier = models.CharField(max_length=20, choices=VolunteerTier.choices)valid_until = models.DateField()started = models.DateTimeField(auto_now_add=True)+ class Meta:+ unique_together = [("user", "tier")]+class AgreementType(models.TextChoices):TERMS_OF_SERVICE_GUI = "TERMS_OF_SERVICE_GUI", "Terms of Service (GUI)"diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex 5e5646e..6102a8e 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -1,6 +1,4 @@import logging-from datetime import datetime, time, timedelta-from datetime import timezone as dt_timezonefrom allauth.account.adapter import get_adapterfrom allauth.account.models import EmailConfirmationHMAC@@ -26,13 +24,10 @@ from polar_sdk.webhooks import WebhookVerificationErrorfrom mwmbl import membership, pricingfrom mwmbl.background import enrich_domain_submission, stats_manager-from mwmbl.crawler_membership import has_crawler_membership, membership_tierfrom mwmbl.exceptions import InvalidRequest-from mwmbl.membership import MembershipTierfrom mwmbl.models import (AgreementType,ApiKey,- CrawlerMembership,Device,DomainEvidence,DomainSubmission,@@ -90,6 +85,8 @@ from mwmbl.platform.schemas import (UserProfileResponse,UserStatsResponse,UserVoteHistory,+ VolunteerMembershipResponse,+ VolunteerTierResponse,VoteRemoveRequest,VoteRequest,VoteResponse,@@ -101,7 +98,8 @@ from mwmbl.quota import get_monthly_combined_search_api_count, get_monthly_combifrom mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cachefrom mwmbl.signals import schedule_blacklist_rebuildfrom mwmbl.usernames import generate_username-from mwmbl.utils import normalize_domain, utc_today, validate_domain+from mwmbl.utils import normalize_domain, validate_domain+from mwmbl.volunteer_membership import current_volunteer_membership, user_combined_search_monthly_limitlogger = logging.getLogger(__name__)@@ -1346,24 +1344,53 @@ def list_membership_tiers(request):auth=JWTAuth(),response=MembershipResponse,summary="Get current membership",- description="Returns the user's membership tier, or 404 if they aren't a member. A paid membership "- "takes precedence over a Sprout membership earned by crawling.",+ description="Returns the user's membership tier, or 404 if they aren't a member.",tags=["Membership"],)def get_membership(request):user_membership = Membership.objects.filter(user=request.user).first()- if user_membership is not None:- return user_membership- crawler_membership = CrawlerMembership.objects.filter(user=request.user, valid_until__gte=utc_today()).first()- if crawler_membership is None:+ if user_membership is None:raise InvalidRequest("Not a member.", status=404)- return MembershipResponse(- tier=MembershipTier.SPROUT,- current_period_end=datetime.combine(- crawler_membership.valid_until + timedelta(days=1), time.min, tzinfo=dt_timezone.utc- ),- cancel_at_period_end=False,- source="crawler",+ return user_membership+++ "/membership/volunteer-tiers",+ response=list[VolunteerTierResponse],+ summary="List volunteer tiers",+ description="Returns the tiers earned by crawling rather than bought, with what earns each one and its perks.",+ tags=["Membership"],+)+def list_volunteer_tiers(request):+ return [+ VolunteerTierResponse(+ tier=info.tier,+ name=info.tier.label,+ days_per_month=info.days_per_month,+ min_results_per_day=info.min_results_per_day,+ perks=info.perks,+ )+ for info in membership.VOLUNTEER_TIERS+ ]+++ "/membership/volunteer",+ auth=JWTAuth(),+ response=VolunteerMembershipResponse,+ summary="Get current volunteer membership",+ description="Returns the highest volunteer tier the user has earned by crawling, or 404 if they don't "+ "currently hold one. This is separate from a paid membership, and a user can hold both.",+ tags=["Membership"],+)+def get_volunteer_membership(request):+ volunteer_membership = current_volunteer_membership(request.user.id)+ if volunteer_membership is None:+ raise InvalidRequest("Not a volunteer member.", status=404)+ return VolunteerMembershipResponse(+ tier=volunteer_membership.tier,+ name=volunteer_membership.get_tier_display(),+ valid_until=volunteer_membership.valid_until,)@@ -1372,15 +1399,14 @@ def get_membership(request):auth=JWTAuth(),response=CombinedSearchUsageResponse,summary="Get Combined Search usage",- description="Returns the user's Combined Search usage this month and their limit, which is set by "- "their membership tier.",+ description="Returns the user's Combined Search usage this month and their limit, which is the more "+ "generous of those set by their membership tier and their volunteer tier.",tags=["Membership"],)def get_combined_search_usage(request):- tier = membership_tier(request.user.id)return CombinedSearchUsageResponse(monthly_usage=get_monthly_combined_search_count(request.user.id),- monthly_limit=membership.combined_search_monthly_limit(tier),+ monthly_limit=user_combined_search_monthly_limit(request.user.id),)@@ -1454,7 +1480,9 @@ def create_membership_checkout(request, body: MembershipCheckoutRequest):)def cancel_membership(request):check_email_verified(request)- user_membership = _paid_membership(request.user)+ user_membership = Membership.objects.filter(user=request.user).first()+ if user_membership is None:+ raise InvalidRequest("Not a member.", status=404)if user_membership.cancel_at_period_end:raise InvalidRequest("Membership is already scheduled to cancel.", status=409)try:@@ -1480,7 +1508,9 @@ def cancel_membership(request):)def uncancel_membership(request):check_email_verified(request)- user_membership = _paid_membership(request.user)+ user_membership = Membership.objects.filter(user=request.user).first()+ if user_membership is None:+ raise InvalidRequest("Not a member.", status=404)if not user_membership.cancel_at_period_end:raise InvalidRequest("Membership is not scheduled to cancel.", status=409)try:@@ -1507,7 +1537,9 @@ def uncancel_membership(request):)def change_membership(request, body: MembershipChangeRequest):check_email_verified(request)- user_membership = _paid_membership(request.user)+ user_membership = Membership.objects.filter(user=request.user).first()+ if user_membership is None:+ raise InvalidRequest("Not a member.", status=404)if user_membership.tier == body.tier:raise InvalidRequest("Already on this tier.", status=409)# Changing tier would leave the cancellation in place, which is rarely what anyone wants;@@ -1534,19 +1566,6 @@ def change_membership(request, body: MembershipChangeRequest):return _save_membership_update(user_membership, tier=tier, current_period_end=result.current_period_end)-def _paid_membership(user) -> Membership:- """The user's paid membership, for the endpoints that change it in Polar."""- user_membership = Membership.objects.filter(user=user).first()- if user_membership is not None:- return user_membership- if has_crawler_membership(user.id):- raise InvalidRequest(- "Memberships earned by crawling can't be cancelled or changed. Buy a membership to choose a tier.",- status=409,- )- raise InvalidRequest("Not a member.", status=404)--def _save_membership_update(user_membership, **changes):"""Record a change made in Polar on the Membership row, unless a webhook changed it during the Polar call.diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.pyindex 5bc67ba..0dffa89 100644--- a/mwmbl/platform/schemas.py+++ b/mwmbl/platform/schemas.py@@ -1,10 +1,10 @@-from datetime import datetime+from datetime import date, datetimefrom typing import Literal, Optionalfrom ninja import Field, ModelSchema, Schemafrom pydantic import model_validator-from mwmbl.membership import MembershipTier+from mwmbl.membership import MembershipTier, VolunteerTierfrom mwmbl.models import AgreementType, DomainSubmission, MarketingSource@@ -57,8 +57,21 @@ class MembershipResponse(Schema):tier: MembershipTiercurrent_period_end: Optional[datetime]cancel_at_period_end: bool- # "crawler" memberships are earned by crawling rather than bought, so there is nothing to cancel or change.- source: Literal["paid", "crawler"] = "paid"+++class VolunteerTierResponse(Schema):+ tier: VolunteerTier+ name: str+ days_per_month: int+ min_results_per_day: int+ perks: list[str]+++class VolunteerMembershipResponse(Schema):+ tier: VolunteerTier+ name: str+ # The last day the membership is valid, unless the user earns it again before then.+ valid_until: dateclass CombinedSearchUsageResponse(Schema):diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 982f29f..933f053 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -299,12 +299,8 @@ CURRENT_AGREEMENT_VERSIONS = {# Combined Search - the v2 endpoint that pools the Mwmbl index, Staan and Wikipedia and# ranks the union with its own LTR model. Gated behind login, like Super Search, which it is# meant to replace. Monthly limits for web (JWT) callers, keyed by-# mwmbl.membership.MembershipTier value; "free" is signed-in users without a membership.-COMBINED_SEARCH_MONTHLY_LIMITS = {"free": 30, "sprout": 300, "sapling": 1_500, "canopy": 1_500}-# Crawling on this many days in a calendar month earns a free Sprout membership. A day counts-# once the user has submitted at least CRAWLER_MEMBERSHIP_MIN_RESULTS results that day.-CRAWLER_MEMBERSHIP_DAYS = 3-CRAWLER_MEMBERSHIP_MIN_RESULTS = 100+# mwmbl.membership.MembershipTier or VolunteerTier value; "free" is signed-in users without either.+COMBINED_SEARCH_MONTHLY_LIMITS = {"free": 30, "sprout": 300, "sapling": 1_500, "canopy": 1_500, "pollinator": 300}# Its own model artifact, so Combined Search can be retrained on the pooled candidate set# without moving standard search's ranking. Falls back to RUST_MODEL_PATH until trained.COMBINED_MODEL_PATH = Path(__file__).parent / "resources" / "model-combined.xgb"diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.pyindex a0d796a..4592eb3 100644--- a/mwmbl/tinysearchengine/combined_search.py+++ b/mwmbl/tinysearchengine/combined_search.py@@ -41,7 +41,6 @@ from ninja_jwt.authentication import JWTAuthfrom pydantic import Fieldfrom mwmbl import pricing-from mwmbl.crawler_membership import membership_tierfrom mwmbl.format import format_result_v2from mwmbl.indexer.index_batches import index_new_results_against_queryfrom mwmbl.indexer.seed_crawl import (@@ -52,7 +51,6 @@ from mwmbl.indexer.seed_crawl import (start_seed_crawl,)from mwmbl.indexer.seed_domains import published_seed_domains-from mwmbl.membership import combined_search_monthly_limitfrom mwmbl.models import UserBillingfrom mwmbl.quota import (check_rate_limit,@@ -67,6 +65,7 @@ from mwmbl.tinysearchengine.indexer import Documentfrom mwmbl.tinysearchengine.rank import find_blacklisted_urlsfrom mwmbl.tinysearchengine.search import SearchResponsefrom mwmbl.tinysearchengine.staan import get_staan_results+from mwmbl.volunteer_membership import user_combined_search_monthly_limitlogger = getLogger(__name__)@@ -286,8 +285,7 @@ def init_router(ranker) -> None:"to allow more.",)else:- tier = await sync_to_async(membership_tier)(user.id)- monthly_limit = combined_search_monthly_limit(tier)+ monthly_limit = await sync_to_async(user_combined_search_monthly_limit)(user.id)# 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.diff --git a/mwmbl/volunteer_membership.py b/mwmbl/volunteer_membership.pynew file mode 100644index 0000000..8ccc53e--- /dev/null+++ b/mwmbl/volunteer_membership.py@@ -0,0 +1,74 @@+"""Volunteer tiers earned by crawling, and the Combined Search limit a user gets from them and their paid membership."""++import calendar+from datetime import date++from mwmbl.membership import VOLUNTEER_TIERS, combined_search_monthly_limit+from mwmbl.models import Membership, MwmblUser, UserStats, VolunteerMembership+from mwmbl.utils import utc_today++TIER_RANK = {info.tier.value: rank for rank, info in enumerate(VOLUNTEER_TIERS)}+++def end_of_next_month(day: date) -> date:+ year, month = (day.year + 1, 1) if day.month == 12 else (day.year, day.month + 1)+ return date(year, month, calendar.monthrange(year, month)[1])+++def update_volunteer_memberships(user: MwmblUser, today: date) -> None:+ """Grant or extend each volunteer tier the user has earned by crawling this month.++ Called after every batch of results, so a tier starts the moment the user reaches its+ threshold, and a grant that failed is retried on their next batch. Once this month has earned+ every tier, it costs one query. A grant never shortens a membership, so a longer one set by+ hand in the admin survives.+ """+ valid_until = end_of_next_month(today)+ extended = set(+ VolunteerMembership.objects.filter(user=user, valid_until__gte=valid_until).values_list("tier", flat=True)+ )+ pending = [info for info in VOLUNTEER_TIERS if info.tier not in extended]+ if not pending:+ return++ daily_results = list(+ UserStats.objects.filter(user=user, date__gte=today.replace(day=1), date__lte=today).values_list(+ "num_results", flat=True+ )+ )+ for info in pending:+ days_crawled = sum(num_results >= info.min_results_per_day for num_results in daily_results)+ if days_crawled < info.days_per_month:+ continue+ _, created = VolunteerMembership.objects.get_or_create(+ user=user, tier=info.tier, defaults={"valid_until": valid_until}+ )+ if not created:+ VolunteerMembership.objects.filter(user=user, tier=info.tier, valid_until__lt=valid_until).update(+ valid_until=valid_until+ )+++def current_volunteer_memberships(user_ids) -> dict[int, VolunteerMembership]:+ """Each user's highest unexpired volunteer membership, for those who have one."""+ best = {}+ for volunteer_membership in VolunteerMembership.objects.filter(user_id__in=user_ids, valid_until__gte=utc_today()):+ held = best.get(volunteer_membership.user_id)+ if held is None or TIER_RANK[volunteer_membership.tier] > TIER_RANK[held.tier]:+ best[volunteer_membership.user_id] = volunteer_membership+ return best+++def current_volunteer_membership(user_id: int) -> VolunteerMembership | None:+ return current_volunteer_memberships([user_id]).get(user_id)+++def user_combined_search_monthly_limit(user_id: int) -> int:+ """The more generous of the limits from the user's paid membership and their volunteer tier.++ Volunteer allowances are set independently of the paid tiers, so neither always wins.+ """+ paid_tier = Membership.objects.filter(user_id=user_id).values_list("tier", flat=True).first()+ volunteer_membership = current_volunteer_membership(user_id)+ volunteer_tier = volunteer_membership.tier if volunteer_membership else None+ return max(combined_search_monthly_limit(paid_tier), combined_search_monthly_limit(volunteer_tier))diff --git a/test/test_admin_paying_users.py b/test/test_admin_paying_users.pyindex 6254269..6e9f8fb 100644--- a/test/test_admin_paying_users.py+++ b/test/test_admin_paying_users.py@@ -6,7 +6,7 @@ from django.core.cache import cachefrom fakeredis import FakeConnectionfrom mwmbl import quota-from mwmbl.models import ApiKey, CrawlerMembership, Membership, UserBilling+from mwmbl.models import ApiKey, Membership, UserBilling, VolunteerMembershipfrom mwmbl.templatetags.money import minor_unitsfrom mwmbl.utils import utc_today@@ -144,18 +144,31 @@ def test_seed_search_usage_by_tier(staff_client):assert [row["user"].username for row in seed_search["top_users"]] == ["free_user", "sprout_member"]-def test_seed_search_counts_crawler_members_as_sprout(staff_client):- crawler = User.objects.create_user(username="crawler_member")- CrawlerMembership.objects.create(user=crawler, valid_until=utc_today())- quota.increment_monthly_combined_search(crawler.id)+def test_seed_search_counts_volunteers_under_their_tier(staff_client):+ volunteer = User.objects.create_user(username="volunteer")+ VolunteerMembership.objects.create(user=volunteer, tier="pollinator", valid_until=utc_today())+ quota.increment_monthly_combined_search(volunteer.id)response = staff_client.get(PAYING_USERS_URL)by_tier = {tier["tier"]: tier for tier in response.context["seed_search"]["by_tier"]}- assert by_tier["sprout"]["users"] == 1+ assert by_tier["pollinator"] == {"tier": "pollinator", "users": 1, "queries": 1, "at_limit": 0, "limit": 300}assert by_tier["free"]["users"] == 0+def test_seed_search_counts_a_paid_volunteer_under_the_tier_that_sets_their_limit(staff_client):+ member = User.objects.create_user(username="sapling_volunteer")+ Membership.objects.create(user=member, tier="sapling", polar_subscription_id="sub_sapling")+ VolunteerMembership.objects.create(user=member, tier="pollinator", valid_until=utc_today())+ quota.increment_monthly_combined_search(member.id)++ response = staff_client.get(PAYING_USERS_URL)++ by_tier = {tier["tier"]: tier for tier in response.context["seed_search"]["by_tier"]}+ assert by_tier["sapling"]["users"] == 1+ assert by_tier["pollinator"]["users"] == 0++def test_seed_search_skips_deleted_users(staff_client):deleted = User.objects.create_user(username="deleted_user")quota.increment_monthly_combined_search(deleted.id)diff --git a/test/test_combined_search.py b/test/test_combined_search.pyindex 832c588..9417b18 100644--- a/test/test_combined_search.py+++ b/test/test_combined_search.py@@ -23,8 +23,8 @@ from ninja_jwt.tokens import RefreshTokenimport mwmbl.tinysearchengine.combined_search as combined_searchfrom mwmbl import pricingfrom mwmbl.indexer import seed_crawl-from mwmbl.membership import MembershipTier-from mwmbl.models import ApiKey, CrawlerMembership, Membership, UserBilling, generate_api_key+from mwmbl.membership import MembershipTier, VolunteerTier+from mwmbl.models import ApiKey, Membership, UserBilling, VolunteerMembership, generate_api_keyfrom mwmbl.quota import (_combined_search_api_monthly_key,_combined_search_monthly_key,@@ -289,9 +289,9 @@ def _join(user, tier):@pytest.mark.django_db-def test_a_crawler_membership_gives_the_sprout_limit(client, user, access_token, fresh_quota, stub_sources):+def test_a_volunteer_membership_sets_the_limit(client, user, access_token, fresh_quota, stub_sources):stub_sources()- CrawlerMembership.objects.create(user=user, valid_until=utc_today())+ VolunteerMembership.objects.create(user=user, tier=VolunteerTier.POLLINATOR, valid_until=utc_today())cache.set(_combined_search_monthly_key(user.id), 299, timeout=3600)last_allowed = _get(client, access_token)diff --git a/test/test_crawler_membership.py b/test/test_crawler_membership.pydeleted file mode 100644index 7692826..0000000--- a/test/test_crawler_membership.py+++ /dev/null@@ -1,204 +0,0 @@-"""Tests for free Sprout memberships earned by crawling."""--from datetime import date, datetime, timezone-from types import SimpleNamespace-from unittest.mock import patch--import fakeredis-import pytest-from allauth.account.models import EmailAddress-from django.test import Client-from ninja_jwt.tokens import RefreshToken--from mwmbl.crawler.stats import StatsManager-from mwmbl.crawler_membership import end_of_next_month, membership_tier-from mwmbl.membership import MembershipTier-from mwmbl.models import CrawlerMembership, Membership, MwmblUser--TODAY = date(2026, 10, 17)-ENOUGH_RESULTS = 100---def user(db):- user = MwmblUser.objects.create_user(username="crawler", email="[email protected]", password="testpass123")- EmailAddress.objects.create(user=user, email="[email protected]", verified=True, primary=True)- return user---def today():- with (- patch("mwmbl.crawler_membership.utc_today", return_value=TODAY),- patch("mwmbl.platform.api.utc_today", return_value=TODAY),- ):- yield TODAY---def _crawl(user, day: date, num_results: int = ENOUGH_RESULTS) -> None:- results = SimpleNamespace(results=[object()] * num_results)- with patch("mwmbl.crawler.stats.utc_today", return_value=day):- StatsManager(fakeredis.FakeRedis()).record_results(results, user)---def auth_headers(user):- return {"HTTP_AUTHORIZATION": f"Bearer {RefreshToken.for_user(user).access_token}"}--- "day, expected",- [- (date(2026, 10, 17), date(2026, 11, 30)),- (date(2026, 12, 1), date(2027, 1, 31)),- (date(2028, 1, 31), date(2028, 2, 29)),- ],-)-def test_end_of_next_month(day, expected):- assert end_of_next_month(day) == expected---def test_membership_is_granted_on_the_third_crawl_day(user):- _crawl(user, date(2026, 10, 1))- _crawl(user, date(2026, 10, 5))- assert not CrawlerMembership.objects.filter(user=user).exists()-- _crawl(user, date(2026, 10, 9))-- assert CrawlerMembership.objects.get(user=user).valid_until == date(2026, 11, 30)---def test_several_batches_on_one_day_count_as_one_day(user):- for _ in range(3):- _crawl(user, date(2026, 10, 1))- _crawl(user, date(2026, 10, 2))-- assert not CrawlerMembership.objects.filter(user=user).exists()--[email protected]("num_results", [0, ENOUGH_RESULTS - 1])-def test_days_with_too_few_results_do_not_count(user, num_results):- _crawl(user, date(2026, 10, 1))- _crawl(user, date(2026, 10, 2))- _crawl(user, date(2026, 10, 3), num_results=num_results)-- assert not CrawlerMembership.objects.filter(user=user).exists()---def test_membership_is_granted_when_a_day_reaches_the_minimum(user):- _crawl(user, date(2026, 10, 1))- _crawl(user, date(2026, 10, 2))- _crawl(user, date(2026, 10, 3), num_results=ENOUGH_RESULTS - 1)- _crawl(user, date(2026, 10, 3), num_results=1)-- assert CrawlerMembership.objects.get(user=user).valid_until == date(2026, 11, 30)---def test_days_in_earlier_months_do_not_count(user):- _crawl(user, date(2026, 9, 29))- _crawl(user, date(2026, 9, 30))- _crawl(user, date(2026, 10, 1))-- assert not CrawlerMembership.objects.filter(user=user).exists()---def test_qualifying_again_extends_the_membership(user):- for day in (1, 2, 3):- _crawl(user, date(2026, 10, day))- for day in (1, 2, 3):- _crawl(user, date(2026, 11, day))-- assert CrawlerMembership.objects.get(user=user).valid_until == date(2026, 12, 31)---def test_qualifying_does_not_shorten_a_longer_membership(user):- CrawlerMembership.objects.create(user=user, valid_until=date(2027, 6, 30))- for day in (1, 2, 3):- _crawl(user, date(2026, 10, day))-- assert CrawlerMembership.objects.get(user=user).valid_until == date(2027, 6, 30)---def test_a_failed_grant_is_retried_on_the_next_batch(user):- _crawl(user, date(2026, 10, 1))- _crawl(user, date(2026, 10, 2))- with patch("mwmbl.crawler_membership.CrawlerMembership.objects.get_or_create", side_effect=RuntimeError):- with pytest.raises(RuntimeError):- _crawl(user, date(2026, 10, 3))-- _crawl(user, date(2026, 10, 3))-- assert CrawlerMembership.objects.get(user=user).valid_until == date(2026, 11, 30)---def test_crawler_membership_gives_sprout(user, today):- CrawlerMembership.objects.create(user=user, valid_until=today)- assert membership_tier(user.id) == MembershipTier.SPROUT---def test_expired_crawler_membership_gives_nothing(user, today):- CrawlerMembership.objects.create(user=user, valid_until=date(2026, 10, 16))- assert membership_tier(user.id) is None---def test_paid_membership_wins_over_crawler_membership(user, today):- CrawlerMembership.objects.create(user=user, valid_until=today)- Membership.objects.create(user=user, tier=MembershipTier.SAPLING, polar_subscription_id="sub_1")- assert membership_tier(user.id) == MembershipTier.SAPLING---def test_get_membership_returns_crawler_membership(user, today):- CrawlerMembership.objects.create(user=user, valid_until=date(2026, 11, 30))- response = Client().get("/api/v1/platform/membership", **auth_headers(user))-- assert response.status_code == 200- assert response.json() == {- "tier": "sprout",- "current_period_end": datetime(2026, 12, 1, tzinfo=timezone.utc).isoformat().replace("+00:00", "Z"),- "cancel_at_period_end": False,- "source": "crawler",- }---def test_get_membership_is_404_when_the_crawler_membership_has_expired(user, today):- CrawlerMembership.objects.create(user=user, valid_until=date(2026, 10, 16))- response = Client().get("/api/v1/platform/membership", **auth_headers(user))-- assert response.status_code == 404---def test_get_membership_marks_paid_membership(user):- Membership.objects.create(user=user, tier=MembershipTier.SAPLING, polar_subscription_id="sub_1")- response = Client().get("/api/v1/platform/membership", **auth_headers(user))-- assert response.status_code == 200- assert response.json()["source"] == "paid"---def test_get_membership_prefers_the_paid_membership(user, today):- CrawlerMembership.objects.create(user=user, valid_until=today)- Membership.objects.create(user=user, tier=MembershipTier.CANOPY, polar_subscription_id="sub_1")- response = Client().get("/api/v1/platform/membership", **auth_headers(user))-- assert response.json()["tier"] == "canopy"- assert response.json()["source"] == "paid"--- "path, body",- [("cancel", None), ("uncancel", None), ("change", {"tier": "sapling"})],-)-def test_crawler_memberships_cannot_be_cancelled_or_changed(user, today, path, body):- CrawlerMembership.objects.create(user=user, valid_until=today)- response = Client().post(- f"/api/v1/platform/membership/{path}", body, content_type="application/json", **auth_headers(user)- )-- assert response.status_code == 409---def test_crawler_membership_sets_the_combined_search_limit(user, today):- CrawlerMembership.objects.create(user=user, valid_until=today)- with patch("mwmbl.platform.api.get_monthly_combined_search_count", return_value=0):- response = Client().get("/api/v1/platform/combined-search/usage", **auth_headers(user))-- assert response.json()["monthly_limit"] == 300diff --git a/test/test_volunteer_membership.py b/test/test_volunteer_membership.pynew file mode 100644index 0000000..3e40a2d--- /dev/null+++ b/test/test_volunteer_membership.py@@ -0,0 +1,235 @@+"""Tests for volunteer tiers earned by crawling."""++from datetime import date+from types import SimpleNamespace+from unittest.mock import patch++import fakeredis+import pytest+from django.test import Client+from ninja_jwt.tokens import RefreshToken++from mwmbl import membership+from mwmbl.crawler.stats import StatsManager+from mwmbl.membership import MembershipTier, VolunteerTier, VolunteerTierInfo+from mwmbl.models import Membership, MwmblUser, VolunteerMembership+from mwmbl.volunteer_membership import end_of_next_month, user_combined_search_monthly_limit++TODAY = date(2026, 10, 17)+ENOUGH_RESULTS = 100+POLLINATOR = VolunteerTier.POLLINATOR+++def user(db):+ return MwmblUser.objects.create_user(username="crawler", email="[email protected]", password="testpass123")+++def today():+ with patch("mwmbl.volunteer_membership.utc_today", return_value=TODAY):+ yield TODAY+++def two_tiers(monkeypatch):+ """A second, higher volunteer tier, as if one had been added to VOLUNTEER_TIERS."""+ higher = VolunteerTierInfo(tier=POLLINATOR, days_per_month=5, min_results_per_day=ENOUGH_RESULTS, perks=[])+ lower = VolunteerTierInfo(tier="lower", days_per_month=3, min_results_per_day=ENOUGH_RESULTS, perks=[])+ tiers = [lower, higher]+ monkeypatch.setattr("mwmbl.volunteer_membership.VOLUNTEER_TIERS", tiers)+ monkeypatch.setattr("mwmbl.volunteer_membership.TIER_RANK", {"lower": 0, POLLINATOR: 1})+ return tiers+++def _crawl(user, day: date, num_results: int = ENOUGH_RESULTS) -> None:+ results = SimpleNamespace(results=[object()] * num_results)+ with patch("mwmbl.crawler.stats.utc_today", return_value=day):+ StatsManager(fakeredis.FakeRedis()).record_results(results, user)+++def _valid_until(user, tier=POLLINATOR) -> date | None:+ return VolunteerMembership.objects.filter(user=user, tier=tier).values_list("valid_until", flat=True).first()+++def auth_headers(user):+ return {"HTTP_AUTHORIZATION": f"Bearer {RefreshToken.for_user(user).access_token}"}+++ "day, expected",+ [+ (date(2026, 10, 17), date(2026, 11, 30)),+ (date(2026, 12, 1), date(2027, 1, 31)),+ (date(2028, 1, 31), date(2028, 2, 29)),+ ],+)+def test_end_of_next_month(day, expected):+ assert end_of_next_month(day) == expected+++def test_pollinator_is_earned_on_the_third_crawl_day(user):+ _crawl(user, date(2026, 10, 1))+ _crawl(user, date(2026, 10, 5))+ assert _valid_until(user) is None++ _crawl(user, date(2026, 10, 9))++ assert _valid_until(user) == date(2026, 11, 30)+++def test_several_batches_on_one_day_count_as_one_day(user):+ for _ in range(3):+ _crawl(user, date(2026, 10, 1))+ _crawl(user, date(2026, 10, 2))++ assert _valid_until(user) is None++[email protected]("num_results", [0, ENOUGH_RESULTS - 1])+def test_days_with_too_few_results_do_not_count(user, num_results):+ _crawl(user, date(2026, 10, 1))+ _crawl(user, date(2026, 10, 2))+ _crawl(user, date(2026, 10, 3), num_results=num_results)++ assert _valid_until(user) is None+++def test_a_day_counts_once_it_reaches_the_minimum(user):+ _crawl(user, date(2026, 10, 1))+ _crawl(user, date(2026, 10, 2))+ _crawl(user, date(2026, 10, 3), num_results=ENOUGH_RESULTS - 1)+ _crawl(user, date(2026, 10, 3), num_results=1)++ assert _valid_until(user) == date(2026, 11, 30)+++def test_days_in_earlier_months_do_not_count(user):+ _crawl(user, date(2026, 9, 29))+ _crawl(user, date(2026, 9, 30))+ _crawl(user, date(2026, 10, 1))++ assert _valid_until(user) is None+++def test_earning_it_again_extends_the_membership(user):+ for day in (1, 2, 3):+ _crawl(user, date(2026, 10, day))+ for day in (1, 2, 3):+ _crawl(user, date(2026, 11, day))++ assert _valid_until(user) == date(2026, 12, 31)+++def test_earning_it_does_not_shorten_a_longer_membership(user):+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=date(2027, 6, 30))+ for day in (1, 2, 3):+ _crawl(user, date(2026, 10, day))++ assert _valid_until(user) == date(2027, 6, 30)+++def test_a_failed_grant_is_retried_on_the_next_batch(user):+ _crawl(user, date(2026, 10, 1))+ _crawl(user, date(2026, 10, 2))+ with patch("mwmbl.volunteer_membership.VolunteerMembership.objects.get_or_create", side_effect=RuntimeError):+ with pytest.raises(RuntimeError):+ _crawl(user, date(2026, 10, 3))++ _crawl(user, date(2026, 10, 3))++ assert _valid_until(user) == date(2026, 11, 30)+++def test_each_tier_is_earned_at_its_own_threshold(user, two_tiers):+ for day in (1, 2, 3):+ _crawl(user, date(2026, 10, day))+ assert _valid_until(user, "lower") == date(2026, 11, 30)+ assert _valid_until(user) is None++ for day in (4, 5):+ _crawl(user, date(2026, 10, day))++ assert _valid_until(user) == date(2026, 11, 30)+++def test_every_volunteer_tier_has_a_combined_search_limit(settings):+ for info in membership.VOLUNTEER_TIERS:+ assert info.tier.value in settings.COMBINED_SEARCH_MONTHLY_LIMITS+++def test_pollinator_sets_the_combined_search_limit(user, today):+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=today)+ assert user_combined_search_monthly_limit(user.id) == 300+++def test_an_expired_volunteer_membership_gives_the_free_limit(user, today):+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=date(2026, 10, 16))+ assert user_combined_search_monthly_limit(user.id) == 30+++ "paid_limit, pollinator_limit, expected",+ [(1_500, 300, 1_500), (300, 1_000, 1_000)],+)+def test_the_more_generous_limit_applies(user, today, settings, paid_limit, pollinator_limit, expected):+ settings.COMBINED_SEARCH_MONTHLY_LIMITS = {+ **settings.COMBINED_SEARCH_MONTHLY_LIMITS,+ "sprout": paid_limit,+ "pollinator": pollinator_limit,+ }+ Membership.objects.create(user=user, tier=MembershipTier.SPROUT, polar_subscription_id="sub_1")+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=today)++ assert user_combined_search_monthly_limit(user.id) == expected+++def test_list_volunteer_tiers():+ response = Client().get("/api/v1/platform/membership/volunteer-tiers")++ assert response.status_code == 200+ assert response.json()[0] == {+ "tier": "pollinator",+ "name": "Pollinator",+ "days_per_month": 3,+ "min_results_per_day": 100,+ "perks": membership.VOLUNTEER_TIERS[0].perks,+ }+++def test_get_volunteer_membership(user, today):+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=date(2026, 11, 30))+ response = Client().get("/api/v1/platform/membership/volunteer", **auth_headers(user))++ assert response.status_code == 200+ assert response.json() == {"tier": "pollinator", "name": "Pollinator", "valid_until": "2026-11-30"}+++def test_get_volunteer_membership_returns_the_highest_tier(user, today, two_tiers):+ VolunteerMembership.objects.create(user=user, tier="lower", valid_until=date(2026, 12, 31))+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=date(2026, 11, 30))+ response = Client().get("/api/v1/platform/membership/volunteer", **auth_headers(user))++ assert response.json()["tier"] == "pollinator"+++def test_get_volunteer_membership_is_404_once_expired(user, today):+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=date(2026, 10, 16))+ response = Client().get("/api/v1/platform/membership/volunteer", **auth_headers(user))++ assert response.status_code == 404+++def test_volunteer_membership_is_not_a_paid_membership(user, today):+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=today)+ response = Client().get("/api/v1/platform/membership", **auth_headers(user))++ assert response.status_code == 404+++def test_pollinator_sets_the_usage_limit(user, today):+ VolunteerMembership.objects.create(user=user, tier=POLLINATOR, valid_until=today)+ with patch("mwmbl.platform.api.get_monthly_combined_search_count", return_value=0):+ response = Client().get("/api/v1/platform/combined-search/usage", **auth_headers(user))++ assert response.json()["monthly_limit"] == 300